Python 3D Academyবাংলা

JSON

🌍 In real life. When a phone app saves your settings, or a website sends your profile to your phone, the data travels as plain text in an agreed format, so any program in any language can read it. The most common of those formats is JSON, and it looks almost exactly like Python's dictionaries and lists.

The idea in one sentence: json.dump/json.dumps turn Python dictionaries and lists into JSON text, and json.load/json.loads turn JSON text back into Python data.

Its words:

  • JSON: a text format for data: objects {}, arrays [], strings in double quotes, numbers, true, false, null
  • json.dumps(data) / json.loads(text): to and from a string
  • json.dump(data, f) / json.load(f): to and from a file
  • indent=2: spreads the JSON over lines, easy for people to read

Step by step, for json.loads('{"theme": "dark"}'):

  1. Python reads the JSON object {...} and makes a dictionary.
  2. "theme" becomes a Python string key, and "dark" its value.
  3. The result is {'theme': 'dark'}, ready to use like any dictionary.
import json

pet = {"name": "Rex", "age": 3, "vaccinated": True, "owner": None}
text = json.dumps(pet)
print(text)
back = json.loads(text)
print(back["name"], back["vaccinated"])

json.load(f) reads JSON straight from a file, and json.dump(data, f) writes it. What comes out is ordinary Python data, so you use it like any dictionary:

import json

with open("settings.json") as f:
    settings = json.load(f)

print(settings["theme"])
print(settings.get("font", "big"))

To change a JSON file: load it, change the data, then dump it back. indent=2 makes the file easy for people to read.

import json

with open("settings.json") as f:
    settings = json.load(f)
settings["volume"] = 9

with open("settings.json", "w") as f:
    json.dump(settings, f, indent=2)

with open("settings.json") as f:
    print(f.read())

Why JSON? Your program's dictionary lives only in memory and vanishes when the program ends. Saving it as JSON keeps it in a file for next time, in a format that a web page, a phone app or a program in another language can read too.

Mistakes and edge cases.

  • Single quotes in JSON text. json.loads("{'a': 1}") gives json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1). JSON strings use double quotes.
  • Data JSON can't hold. json.dumps({1, 2}) gives TypeError: Object of type set is not JSON serializable. Turn a set into a list first.
  • Number keys come back as strings. {1: "a"} saved and loaded again is {'1': 'a'}: JSON keys are always strings.
  • Tuples come back as lists. (1, 2) is saved as [1, 2].

Quiz

  1. What does this print?

    import json
    print(json.dumps({"ok": True, "items": [1, 2]}))
  2. What does this print?

    import json
    data = json.loads('{"a": null, "b": false}')
    print(data)
  3. Which is valid JSON?

    • {"name": "Bo"}
    • {'name': 'Bo'}
    • {"name": "Bo",}
  4. What does this print?

    import json
    
    with open("d.json", "w") as f:
        json.dump({"x": 1}, f)
    with open("d.json") as f:
        print(json.load(f)["x"] + 1)
  5. Which line has a mistake?

    import json
    
    text = "{'theme': 'dark'}"
    settings = json.loads(text)
    print(settings["theme"])

Coding tasks

  1. Write get_theme(filename) that loads the JSON file and returns its "theme".

  2. Write to_json(data) that returns data as JSON text.

  3. scores.json maps names to scores. Write add_point(filename, name) that adds 1 to that name's score and saves the file again (with plain json.dump, no indent).