← Python lessons

Python JSON: loads, dumps, load and dump

Python's json module converts JSON text into Python values and back. Use loads() and dumps() for strings, load() and dump() for files.

Read a JSON string with loads

JSON stores data as text. json.loads() turns a JSON object into a dictionary.

import json

player = json.loads('{"name": "Ada", "ready": true, "team": null}')
print(player["name"])
print(player["ready"])
print(player["team"])

This prints Ada, True and None. JSON arrays become lists; false becomes False.

Make a JSON string with dumps

json.dumps() returns a string. JSON uses double quotes around keys and text.

import json

player = {"name": "Ada", "scores": [8, 6]}
text = json.dumps(player)
print(text)

This prints {"name": "Ada", "scores": [8, 6]}. Use indent=2 for indented output.

Write and read a JSON file

Pass an open file to dump() or load(). The functions without s work with files.

import json

with open("lesson-player.json", "w", encoding="utf-8") as target:
    json.dump({"name": "Ada", "score": 8}, target)
with open("lesson-player.json", "r", encoding="utf-8") as source:
    player = json.load(source)
print(player["name"], player["score"])

This prints Ada 8. Opening with "w" replaces existing contents.

Handle invalid JSON

Invalid JSON raises json.JSONDecodeError. A trailing comma is not valid JSON.

import json

try:
    json.loads('{"score": 8,}')
except json.JSONDecodeError:
    print("Invalid JSON")

This prints Invalid JSON. JSON cannot directly store every Python object, such as a set.

See also: Dictionaries, Writing files, Try and except.

Your turn

Parse text with json.loads(). Print the player's name and score on one line.

import json

text = '{"name": "Mia", "score": 9}'
# add two lines: parse text into player, then print its name and score

Expected output

Mia 9

Practise this in the free Python course, where every exercise checks your code instantly.