Lesson 11
JSON Files — loads, dumps, load, and dump
Convert between Python dicts and JSON text with loads and dumps, and move dicts to and from .json files with load and dump.
JSON is a light text format for exchanging data. In Python it lines up with a dict: names and values. The json module converts both ways.
Use the playground at the bottom of this page, then take the quiz.
What you will learn
- Why JSON shows up between programs
json.loadsandjson.dumpsfor a stringjson.loadandjson.dumpfor a.jsonfile- How to walk the dict with
mandp
The idea
JSON (JavaScript Object Notation) is language-independent. A Python service and a web client can both read it. The file extension is .json, and the contents look like a dict written as text.
| Function | Direction |
|---|---|
json.loads(text) |
JSON string → dict |
json.dumps(record) |
dict → JSON string |
json.load(handle) |
JSON file → dict |
json.dump(record, handle) |
dict → JSON file |
loads and dumps never touch a file. load and dump use a text file pointer. Open that file with "r" or "w". A missing file raises FileNotFoundError.
After loads or load, walk the dict with for m, p in record.items(). m is the name. p is the value. JSON objects become dicts. JSON arrays become lists. JSON numbers become int or float, which is different from CSV, where every cell is a string.
dumps is the string form of dump. The teaching notes focus on loads, load, and dump; dumps is the matching way to build the JSON string those notes start from.
The profile below uses a general name and a role. It is not taken from a sample .json file in the notes.
Example
import json
text = '{"label": "Avery Lane", "role": "Guide", "seats": 18}'
record = json.loads(text)
for m, p in record.items():
print(m, "-->", p)
with open("profile.json", "w", encoding="utf-8") as handle:
json.dump(record, handle)
with open("profile.json", "r", encoding="utf-8") as handle:
loaded = json.load(handle)
print(json.dumps(loaded))seats stays a number because JSON numbers are not quoted. The playground prints each pair and then the dumped string. Change role and run again.
Key takeaways
-
JSON text maps to Python dicts and lists
-
loads/dumpswork on strings -
load/dumpwork on.jsonfiles -
Walk pairs with
for m, p in record.items() -
Numbers in JSON stay numbers; CSV cells come back as strings
-
Previous: DictWriter and DictReader
-
Next: The os Module
Loading playground…
Check your understanding
JSON files quiz
JSON stands for:
1 / 10