Reading JSON
Use json.load() and json.loads() to parse JSON data
💻
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Reading a JSON file
Use json.load() to parse a JSON file into a Python object. The result is a regular Python dict, list, or other type — you access it exactly as you would any Python data.
import json
with open("config.json", "r") as file:
config = json.load(file)
print(config["app"]) # access like a dictParsing a JSON string
Use json.loads() (load-string) to parse a JSON string that you already have in memory — for example, an API response.
raw = '{"name": "Alice", "score": 95}'
data = json.loads(raw)
print(data["name"])The s in json.loads() stands for "string". Remember: load() reads from a file, loads() reads from a string.
Instructions
Read a JSON config file and parse a JSON string.
- Import
json. - Open
config.jsonin read mode. Assignjson.load(file)toconfig. Callprint(config["app"]). Callprint(config["port"]). - Create
raw = '{"name": "Alice", "score": 95}'. Assignjson.loads(raw)todata. Callprint(data["name"]).
# config.json contains:
# {"app": "MyApp", "version": "1.0", "debug": true, "port": 8080}
# Step 1: Import json
# Step 2: Open config.json, load it into config, and print config["app"] and config["port"]
# Step 3: Create raw JSON string, parse with json.loads(), and print the name
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding