dumps and loads

json · Essentials · 7 min

Almost every web API, webhook and config file speaks JSON.

JSON (JavaScript Object Notation) is a text format for structured data: objects ({"key": value}), arrays ([1, 2]), strings, numbers, true, false and null.

The json module has two core functions for strings:

  • json.dumps(obj) ("dump string") serialises a Python object to a JSON str.
  • json.loads(text) ("load string") parses JSON text into Python objects. It also accepts bytes in UTF-8, UTF-16 or UTF-32, so you can pass an HTTP response body directly.

The result of loads is made of plain Python types: dicts, lists, str, int, float, bool and None. There are no special JSON objects to learn; you index into the result like any other dict or list.

A round trip json.loads(json.dumps(x)) gives back an equal value for data made of these basic types, with a few exceptions covered in the type-mapping lesson (tuples become lists, non-string keys become strings).

JSON syntax is stricter than Python's: strings use double quotes, there are no trailing commas, no comments, and the literals are lowercase true/false/null. So str(my_dict) is not JSON; "{'a': True}" fails to parse. Always produce JSON with json.dumps.

Example

import json

user = {"name": "Ann", "age": 31, "admin": False, "tags": ["a", "b"], "boss": None}
text = json.dumps(user)
print(text)
# {"name": "Ann", "age": 31, "admin": false, "tags": ["a", "b"], "boss": null}
print(type(text).__name__)          # str

data = json.loads('{"id": 7, "items": [1.5, 2], "ok": true}')
print(data["items"][0], data["ok"])  # 1.5 True
print(json.loads(b'[1, 2, 3]'))     # [1, 2, 3]

print(str({"a": True}))             # {'a': True}  -- not JSON!

Remember

  • dumps makes a JSON string; loads parses one into dicts, lists and scalars
  • JSON uses double quotes and lowercase true/false/null
  • str(dict) is not JSON; always use json.dumps

Watch out for

  • Building JSON with f-strings or str(); quoting and escaping break as soon as a value contains a quote.

Check yourself

  1. What does json.dumps({'ok': True, 'v': None}) return?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/library/json.html#json.dumps