JSON is a text format for data made of objects, lists, strings, numbers, true/false and null. It maps closely to Python dictionaries and lists, and the json module converts between the two.
The program
import json profile = { "name": "Hedy", "age": 35, "languages": ["Python", "SQL"], "active": True, "manager": None, } with open("profile.json", "w", encoding="utf-8") as f: json.dump(profile, f, indent=2) with open("profile.json", encoding="utf-8") as f: print(f.read()) with open("profile.json", encoding="utf-8") as f: loaded = json.load(f) print(loaded) print("Same data:", loaded == profile)
{
"name": "Hedy",
"age": 35,
"languages": [
"Python",
"SQL"
],
"active": true,
"manager": null
}
{'name': 'Hedy', 'age': 35, 'languages': ['Python', 'SQL'], 'active': True, 'manager': None}
Same data: TrueHow it works
json.dump(data, f)writes the data to the file.indent=2puts each item on its own line, so people can read the file.json.load(f)reads the file and gives back Python objects: objects become dictionaries, arrays become lists.- Look at the file: Python's
TrueandNoneare written as JSON'strueandnull. When the file is loaded, they becomeTrueandNoneagain. dumpandloadwork with files.json.dumps()andjson.loads()(with ans, for "string") do the same with strings.
Types that change
Not every Python type has a JSON form. A tuple is saved as a JSON list, so it comes back as a list. Dictionary keys must be strings, so a number key comes back as a string:
import json data = {"point": (3, 4), 1: "one"} text = json.dumps(data) print(text) print(json.loads(text))
{"point": [3, 4], "1": "one"}
{'point': [3, 4], '1': 'one'}A set or a datetime cannot be saved directly: json.dumps() raises TypeError. Convert them first, for example with list(my_set) or my_date.isoformat().