CSV and JSON files · 3 / 15 Theory

JSON: dumps and loads

JSON (*JavaScript Object Notation*) is the standard format for exchanging data between programs, especially on the internet: web APIs almost always return JSON. It is text, readable by people, and its structure is very similar to Python dictionaries and lists.

{
  "name": "Ana",
  "age": 30,
  "student": true,
  "hobbies": ["reading", "running"],
  "address": null
}

Equivalences between JSON and Python

JSONPython
object {...}dictionary dict
list [...]list list
text "hello"str
number 3 or 3.5int or float
true / falseTrue / False
nullNone

json.loads: from JSON text to Python

loads (from *load string*) converts JSON text into Python objects:

import json

text = '{"name": "Ana", "age": 30, "student": true, "address": null}'

data = json.loads(text)

print(data)                # {'name': 'Ana', 'age': 30, 'student': True, 'address': None}
print(type(data))          # <class 'dict'>
print(data["name"])        # Ana
print(data["student"])     # True

Notice that true becomes True and null becomes None.

items = json.loads('[1, 2, 3.5, "a"]')
print(items)  # [1, 2, 3.5, 'a']

json.dumps: from Python to JSON text

dumps (from *dump string*) does the opposite:

data = {"name": "Ana", "age": 30, "student": True, "address": None}

text = json.dumps(data)
print(text)
# {"name": "Ana", "age": 30, "student": true, "address": null}
print(type(text))  # <class 'str'>

Useful options of dumps

data = {"b": 2, "a": 1, "name": "José"}

print(json.dumps(data, indent=2))
# {
#   "b": 2,
#   "a": 1,
#   "name": "Jos\u00e9"
# }

print(json.dumps(data, ensure_ascii=False))   # {"b": 2, "a": 1, "name": "José"}
print(json.dumps(data, sort_keys=True))       # {"a": 1, "b": 2, "name": "Jos\u00e9"}
  • indent=2 gives a readable format, with line breaks and indentation.
  • ensure_ascii=False leaves accented letters and ñ as they are, instead of escaping them as \u00e9.
  • sort_keys=True sorts the keys alphabetically.

Which types can be converted

The basic types (dictionaries, lists, texts, numbers, booleans and None) are converted without problems. Tuples become lists, and the keys of a dictionary always end up as text:

print(json.dumps({"point": (3, 4), 1: "one"}))
# {"point": [3, 4], "1": "one"}

Other types, such as sets or dates, cannot be converted directly and raise a TypeError:

json.dumps({1, 2, 3})
# TypeError: Object of type set is not JSON serializable

In that case you have to convert them first, for example list(my_set) or date.isoformat().

Practice in Reading a JSON object, Order total and Creating a JSON.