Two functions, and the only difference is the s: json.load reads from an open file, json.loads parses a string you already have.
import json # Make a file to read. Skip this part if you already have one. with open("config.json", "w", encoding="utf-8") as f: f.write('{"site": "pythonmastery", "debug": false, "ports": [8000, 8001]}') with open("config.json", encoding="utf-8") as f: config = json.load(f) print(config["site"]) print(config["ports"][0]) print(type(config["debug"]))
pythonmastery 8000 <class 'bool'>
JSON objects become dictionaries, arrays become lists, true/false become True/False, and null becomes None.
Parsing a string, such as an API response
import json body = '{"user": {"name": "Hedy", "languages": ["python", "go"]}}' data = json.loads(body) print(data["user"]["name"]) print(", ".join(data["user"]["languages"]))
Hedy python, go
If the text came from requests, skip this step: response.json() does the same parse for you.
When a key might be missing
data["email"] raises KeyError if the key isn't there. For optional fields, use .get() with a default.
import json user = json.loads('{"name": "Hedy"}') print(user.get("email", "no email on file"))
no email on file
When it won't parse
JSONDecodeError tells you the line and column where parsing gave up. The usual causes are single quotes (JSON only allows "), a trailing comma after the last item, or a file that is actually empty or HTML. The error page goes through each one.
import json try: json.loads("{'name': 'Hedy'}") except json.JSONDecodeError as e: print(e)
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)