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 dict

Parsing 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.

  1. Import json.
  2. Open config.json in read mode. Assign json.load(file) to config. Call print(config["app"]). Call print(config["port"]).
  3. Create raw = '{"name": "Alice", "score": 95}'. Assign json.loads(raw) to data. Call print(data["name"]).