Decoding and Encoding JSON

Python ships with a powerful and elegant JSON library. It can be imported with:

import json

Decoding JSON with Python

Decoding a string of JSON is as simple as json.loads(…) (short for load string).

It converts:

  • objects to dictionaries
  • arrays to lists,
  • booleans, integers, floats, and strings are recognized for what they are and will be converted into the correct types in Python
  • Any null will be converted into Python’s None type

Here’s an example of json.loads in action:

>>> import json
>>> jsonstring = '{"name": "erik", "age": 38, "married": true}'
>>> json.loads(jsonstring)
{'name': 'erik', 'age': 38, 'married': True}

Encoding JSON with Python

Encoding JSON data with Python is just as easy as decoding. Use json.dumps(…) (short for ‘dump to string’) to convert a Python object consisting of dictionaries, lists, and other native types into a string:

>>> myjson = {'name': 'erik', 'age': 38, 'married': True}
>>> json.dumps(myjson)
'{"name": "erik", "age": 38, "married": true}'

This is the same document, converted back to a string! If you want to make your JSON document more readable for humans, use the indent option:

>>> print(json.dumps(myjson, indent=2))
  "name": "erik",
  "age": 38,
  "married": true