Python The json Module
JSON is a text form for data that many programs and languages can read. dumps turns Python data into a JSON string.
Data to a string
dumps turns a dict into a JSON string. sort_keys=True puts the keys in order.
import json
data = {"name": "Ada", "age": 36}
text = json.dumps(data, sort_keys=True)
print(text)A string back to data
loads does the reverse trip. The string becomes a dict again.
import json
data = json.loads('{"name": "Ada", "age": 36}')
print(data["name"])
print(data["age"])Pretty and sorted
indent=2 spreads the JSON over lines. sort_keys=True keeps the order the same on every run.
import json
data = {"b": 1, "a": 2}
print(json.dumps(data, indent=2, sort_keys=True))JSON in a file
dump writes data to an open file. load reads it back from an open file.
import json
from pathlib import Path
path = Path("data.json")
with open(path, "w", encoding="utf-8") as file:
json.dump({"name": "Ada"}, file, sort_keys=True)
with open(path, "r", encoding="utf-8") as file:
loaded = json.load(file)
print(loaded)Example
import json
from pathlib import Path
settings = {"theme": "dark", "font_size": 14, "show_line_numbers": True}
path = Path("settings.json")
with open(path, "w", encoding="utf-8") as file:
json.dump(settings, file, indent=2, sort_keys=True)
print(path.read_text(encoding="utf-8"))
with open(path, "r", encoding="utf-8") as file:
loaded = json.load(file)
print(loaded)
print(loaded["theme"])Key points
- Serialise: turn data into a text form that can be saved or sent
- Use dumps to turn Python data into a JSON string
- Use loads to turn a JSON string back into Python data
- Use dump to write JSON data into a file
- Use load to read JSON data from a file
- A Python dict becomes a JSON object, and a list becomes a JSON array
- Text, whole numbers and decimal numbers keep their kind in JSON
- True, False and None become true, false and null in JSON
- Use indent=2 to spread JSON over clear, indented lines
- Use sort_keys=True to sort dict keys in the output
- JSON is text that many programs and languages can read as data.
In this example, a settings dict holds three values. dump writes the dict to settings.json with indent and sorted keys. The file text prints first, in JSON spelling. Note the small true in the file. load reads the file back into a dict. The dict prints in Python spelling, with a capital True. The last line reads one value from the loaded dict.
Note
dumps gives you a string and writes no file.
The file job belongs to dump, with no s.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Which function reads JSON data from an open file?