Python JSON
JSON (JavaScript Object Notation) is the most common format for exchanging data between programs. Websites send JSON to apps, configuration files are written in JSON, and many datasets are published as JSON. It looks very much like Python's own dictionaries and lists, and the json module converts between the two in one call.
From Python to JSON text
json.dumps ("dump string") turns Python data into JSON text. indent makes it readable:
import json
student = {"name": "Asha", "age": 21, "languages": ["Python", "C"], "graduated": False, "mentor": None}
print(json.dumps(student))
print(json.dumps(student, indent=2)){"name": "Asha", "age": 21, "languages": ["Python", "C"], "graduated": false, "mentor": null}
{
"name": "Asha",
"age": 21,
"languages": [
"Python",
"C"
],
"graduated": false,
"mentor": null
}Notice the small differences: JSON writes true, false and null where Python has True, False and None, and always uses double quotes. Dictionaries become JSON objects and lists become JSON arrays.
From JSON text to Python
json.loads ("load string") does the opposite, giving you dictionaries and lists you can use at once:
import json
text = '{"city": "Pune", "temps": [31, 29, 33], "sunny": true}'
data = json.loads(text)
print(data["city"], max(data["temps"]), data["sunny"])
print(type(data), type(data["temps"]))Pune 33 True <class 'dict'> <class 'list'>
Invalid JSON, such as single quotes or a missing comma, raises json.JSONDecodeError, which you can catch with try.
JSON files
json.dump and json.load, without the s, write to and read from files directly. This is an easy way to save a program's data between runs:
import json
settings = {"theme": "dark", "font_size": 14, "recent": ["main.py", "notes.txt"]}
with open("settings.json", "w") as f:
json.dump(settings, f, indent=2)
with open("settings.json") as f:
loaded = json.load(f)
loaded["font_size"] += 2
print(loaded)
print(loaded == settings){'theme': 'dark', 'font_size': 16, 'recent': ['main.py', 'notes.txt']}
FalseThe file settings.json appears in the file list: open it to see the JSON text. Tuples are saved as lists, and dictionary keys always become strings in JSON.
Pretty-printing JSON
In the terminal, python3 -m json.tool settings.json prints a JSON file neatly indented, and fails with a clear message if the file is not valid JSON. It is a quick way to check a file.
Practice exercises
- Make a dictionary describing a book and print it as indented JSON.
- Parse the JSON text
'{"items": [3, 5, 8]}'and print the sum of the items. - Save a list of three students as a JSON file, then load it and print each name.
- Write deliberately invalid JSON and catch the error.