Lesson 85 +10 XP

JSON

JSON

JSON is the standard way computers exchange data. Python can convert between JSON text and Python objects with the json module.

JSON to Python: json.loads()

loads() (load string) turns JSON text into a Python dictionary:

import json

x = '{ "name":"John", "age":30, "city":"New York"}'
y = json.loads(x)
print(y["age"])  # 30

Python to JSON: json.dumps()

dumps() (dump string) turns a Python object into JSON text:

import json

x = {
    "name": "John",
    "age": 30,
    "city": "New York"
}
y = json.dumps(x)
print(y)  # {"name": "John", "age": 30, "city": "New York"}

Python types you can convert

dict, list, tuple, str, int, float, bool, None.

print(json.dumps(True))   # true
print(json.dumps(None))   # null
print(json.dumps([1, 2])) # [1, 2]

Format the output

Pass indent for pretty printing:

print(json.dumps(x, indent=4))

Order the keys

sort_keys=True sorts them:

print(json.dumps(x, indent=4, sort_keys=True))

Useful parameters

  • indent: number of spaces.
  • sort_keys: sort keys alphabetically.
  • separators: custom separators.

TL;DR

  • json.loads(text) parses JSON into Python.
  • json.dumps(obj) serializes Python into JSON.
  • All basic Python types convert cleanly.
  • indent and sort_keys pretty-print.