Confused by complex code? Let ourAI-powered Code Explainer demystify it for you. Try it out!
JSON (JavaScript Object Notation) is a lightweight open standard data-interchange file format, that uses human-readable text for transmitting data.
Although you may conclude from the name that it's a Javascript data format. Well, not exactly, JSON is a text format that is completely language-independent and uses conventions that are familiar of most popular programming languages such as Python.
In this tutorial, you will use Python for:
Luckily for us, Python has a built-in modulejson, that is sufficient for our work, let's get started!
Python dictionaries are very similar to JSON format, in fact, you can save a dictionary in very few lines of code:
import json# example dictionary to save as JSONdata = { "first_name": "John", "last_name": "Doe", "email": "john@doe.com", "salary": 1499.9, # just to demonstrate we can use floats as well "age": 17, "is_real": False, # also booleans! "titles": ["The Unknown", "Anonymous"] # also lists!}# save JSON file# 1st optionwith open("data1.json", "w") as f: json.dump(data, f)Once you execute the above code, you'll noticedata1.json file appeared in your working directory. We've opened the file in write mode, and used thejson.dump() function to serialize the Python dictionary as a JSON formatted stream to the opened file.
The resulting file will look something like this:
{ "first_name": "John", "last_name": "Doe", "email": "john@doe.com", "salary": 1499.9, "age": 17, "is_real": false, "titles": [ "The Unknown", "Anonymous" ]}That's one way of saving as JSON, you can usejson.dumps() function as well:
# 2nd optionwith open("data2.json", "w") as f: f.write(json.dumps(data, indent=4))Thejson.dumps() function returns the dictionary as a JSON parsed string, you may want this string for other use, we just saved it to a file just to make you aware that it does exist.
Notice I addedindent=4 this time as a parameter tojson.dumps() function, this will pretty-print JSON array elements and object members, if you useindent=0, it'll only print new lines, and if it'sNone (default), then it's dumped in a single line (not human-readable). Theindentkeyword exists both indump() anddumps() functions.
If your data contains non-ASCII characters, and you don't want Unicode instances on your JSON file (such as\u0623), then you should passensure_ascii=False tojson.dump() function:
unicode_data = { "first_name": "أحمد", "last_name": "علي"}with open("data_unicode.json", "w", encoding="utf-8") as f: json.dump(unicode_data, f, ensure_ascii=False)Resulting file:
{"first_name": "أحمد", "last_name": "علي"}It is pretty straightforward to deserialize JSON files and load them into Python, the below code loads the previously saved JSON file:
# read a JSON file# 1st optionfile_name = "data1.json"with open(file_name) as f: data = json.load(f) print(data)Thejson.load() function will automatically return a Python dictionary, which eases our work with JSON files, here is the output:
{'first_name': 'John', 'last_name': 'Doe', 'email': 'john@doe.com', 'salary': 1499.9, 'age': 17, 'is_real': False, 'titles': ['The Unknown', 'Anonymous']}Similarly, you can also usejson.loads() function to read a string instead:
# 2nd optionfile_name = "data2.json"with open(file_name) as f: data = json.loads(f.read())print(data)So we've read the file content first usingread() method, and then we pass it tojson.loads() function to parse it.
In this section, we'll be using an API request to a remote web server, and save the resulting data to a JSON file, here's the complete code for that:
import requestsimport json# make API request and parse JSON automaticallydata = requests.get("https://jsonplaceholder.typicode.com/users").json()# save all data in a single JSON filefile_name = "user_data.json"with open(file_name, "w") as f: json.dump(data, f, indent=4) print(file_name, "saved successfully!")# or you can save each entry into a filefor user in data: # iterate over `data` list file_name = f"user_{user['id']}.json" with open(file_name, "w") as f: json.dump(user, f, indent=4) print(file_name, "saved successfully!")# load 2nd user for instancefile_name = "user_2.json"with open(file_name) as f: user_data = json.load(f) print(user_data)print("Username:", user_data["username"])Note: To run the above code, you need to install therequests library via:pip install requests
Now you know how to usedump(),dumps(),load() andloads() functions in thejson module and you have the ability to work with JSON data in Python.
As a developer, you'll likely have to interact with it frequently, you'll encounter JSON a lot of times, especially whenworking with REST APIs as we have shown in the example, or when youscraping data from the web.
Every code in this tutorial is included on thefull code page. Check it out!
CheckPython'sjson module official documentation for further details.
Learn also: How to Use Regular Expressions in Python.
Happy Coding ♥
Just finished the article? Why not take your Python skills a notch higher with ourPython Code Assistant? Check it out!
View Full Code Assist My CodingGot a coding query or need some guidance before you comment? Check out thisPython Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!
