Working with JSON
More Python9 min readLesson 5 of 7
5.1 JSON is text, not a Python value
JSON is a text format for structured data, used by APIs and config files. json.loads parses text into Python values: objects become dicts, arrays become lists, strings stay strings, and numbers become int or float. json.dumps goes the other way.
JSON has no tuples, sets or comments. A dict with non-string keys will be converted or rejected, so keep keys as strings when the data crosses a language boundary.
import json
raw = '{"topic": "dictionaries", "minutes": 9}'
lesson = json.loads(raw)
print(lesson["topic"], lesson["minutes"])
lesson["minutes"] = 10
print(json.dumps(lesson))Output
dictionaries 9
{"topic": "dictionaries", "minutes": 10}json.load and json.dump work with file objects. A missing key raises KeyError, so use data.get("key", fallback) when the response shape is not guaranteed. Validation is a separate step; an API can return valid JSON that does not fit your expectations.
