19. JSON

JSON is one of the most common ways to exchange structured data between programs, files, and web APIs. Python’s json module lets you turn Python values into JSON text and parse JSON text back into Python values.

19.1. Encoding JSON

Use json.dumps() to convert Python data into JSON text.

 1import json
 2
 3payload = {
 4    'name': 'Ava',
 5    'scores': [95, 88, 91],
 6    'active': True,
 7}
 8
 9raw = json.dumps(payload)
10print(raw)

19.2. Decoding JSON

Use json.loads() to parse JSON text into Python values.

1import json
2
3raw = '{"name": "Ava", "scores": [95, 88, 91], "active": true}'
4payload = json.loads(raw)
5
6print(payload['name'])
7print(payload['scores'])
8print(payload['active'])

19.3. Pretty printing

When you want JSON output to be easy for humans to read, use indentation and key sorting.

1import json
2
3payload = {
4    'course': 'Python',
5    'students': ['Ava', 'Noah', 'Mia'],
6    'count': 3,
7}
8
9print(json.dumps(payload, indent=2, sort_keys=True))

19.4. Exercise

Create a list of three books as dictionaries and convert it to JSON text. Then parse the JSON text back into Python data and print the title of each book.

19.4.1. Solution

 1import json
 2
 3books = [
 4    {'title': 'Dune', 'author': 'Frank Herbert'},
 5    {'title': 'Foundation', 'author': 'Isaac Asimov'},
 6    {'title': 'Neuromancer', 'author': 'William Gibson'},
 7]
 8
 9raw = json.dumps(books)
10parsed = json.loads(raw)
11
12for book in parsed:
13    print(book['title'])