Back
+15 XP
Concept

Parsing & Serializing JSON (`json.loads` / `json.dumps`)

`json.loads(str)` parses JSON text into Python dictionaries. `json.dumps(dict)` serializes a Python dictionary into a JSON formatted string.

python
import json

data = {"user": "Alice", "admin": True}
raw_json = json.dumps(data)
print(raw_json)  # {"user": "Alice", "admin": true}

parsed = json.loads(raw_json)
print(parsed["user"])  # Alice

# 17. Parsing & Serializing JSON (`json.loads` / `json.dumps`) `json.loads(str)` parses JSON text into Python dictionaries. `json.dumps(dict)` serializes a Python dictionary into a JSON formatted string: ```python import json data = {"user": "Alice", "admin": True} raw_json = json.dumps(data) print(raw_json) # {"user": "Alice", "admin": true} parsed = json.loads(raw_json) print(parsed["user"]) # Alice ``` Notice the 's' in `loads` and `dumps`: it stands for "String". When interacting with raw file streams directly on disk, use `json.load(file_handle)` and `json.dump(data, file_handle)` without the trailing 's'.

Checkpoint

What does Python `True` become when serialized to JSON with `json.dumps()`?

Practice

Convert `payload = {"status": "ok", "code": 200}` to a JSON string using `json.dumps()`, then parse it back with `json.loads()`. Print `parsed["code"]`.

Terminal
01
Tap code blocks below to assemble
Available Blocks