CSV and JSON files · 4 / 15 Theory

JSON in files, nested data and errors

To save JSON in a file and read it later you use json.dump and json.load, without the final "s": they work directly with files instead of with texts.

Saving to a file: json.dump

import json

settings = {"user": "ana", "theme": "dark", "favorites": [3, 7, 9]}

with open("config.json", "w", encoding="utf-8") as f:
    json.dump(settings, f, indent=2, ensure_ascii=False)

Reading from a file: json.load

with open("config.json", "r", encoding="utf-8") as f:
    data = json.load(f)

print(data["user"])        # ana
print(data["favorites"])   # [3, 7, 9]
FunctionWorks withExample
json.loads(text)a textjson.loads(input())
json.dumps(data)a textprint(json.dumps(data))
json.load(f)an open filejson.load(f)
json.dump(data, f)an open filejson.dump(data, f)

Rule to remember it: the s stands for *string* (text).

Nested data

A real JSON usually has objects inside objects and lists of objects. It is traversed just like Python dictionaries and lists, chaining keys and indexes:

text = '''{
  "country": "Spain",
  "cities": [
    {"name": "Madrid", "population": 3300000},
    {"name": "Seville", "population": 680000}
  ]
}'''

data = json.loads(text)

print(data["country"])                    # Spain
print(data["cities"][0]["name"])           # Madrid

for city in data["cities"]:
    print(city["name"], city["population"])
# Madrid 3300000
# Seville 680000

largest = max(data["cities"], key=lambda c: c["population"])
print(largest["name"])                     # Madrid

Modifying and saving again

The usual pattern is to read, change the data in Python and write again:

with open("config.json", "r", encoding="utf-8") as f:
    data = json.load(f)

data["theme"] = "light"
data["favorites"].append(12)

with open("config.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2, ensure_ascii=False)

Common mistakes

Malformed JSON. If the text is not valid JSON, loads raises json.JSONDecodeError. It is a kind of ValueError, so you can catch either one:

try:
    data = json.loads('{"name": "Ana"')    # the closing brace is missing
except json.JSONDecodeError:
    print("Invalid JSON")

The most common mistakes when writing JSON by hand are: using single quotes ('Ana'), forgetting the quotes in the keys ({name: 1}), leaving an extra comma at the end or writing True instead of true.

json.loads("{'a': 1}")     # JSONDecodeError: single quotes not allowed
json.loads('{a: 1}')       # JSONDecodeError: keys need double quotes
json.loads('[1, 2, ]')     # JSONDecodeError: extra comma

A key that does not exist. A JSON may not bring all the fields. Use get or check with in:

data = json.loads('{"name": "Ana"}')

print(data.get("age", "unknown"))   # unknown
print(data["age"])                  # KeyError: 'age'

A file that does not exist. open raises FileNotFoundError; catch it just as you saw in the exceptions lesson.

Validate the data before using it. The result of loads can be a dictionary, a list, a number…; check the type with isinstance(data, dict) if you are not sure what you are receiving.

Practice in Most populated city and Validating JSON.