Beginner   Chapter 105 · 26 min read · Module 8: File Handling

Working with JSON Files

Learning objectives
  • After this chapter you can explain what JSON is and how it maps to Python types.
  • You can convert between Python objects and JSON text with dumps() and loads().
  • You can save data to a file with json.dump() and load it with json.load().
  • You can pretty print JSON using indent and sort_keys.
  • You can handle JSON errors and values that JSON cannot store directly.

JSON stands for JavaScript Object Notation. It is a simple text format for storing structured data such as names, numbers, lists and nested records. Web services, mobile apps and many tools use JSON to exchange data, and it is also a great choice for saving settings and small databases.

JSON looks a lot like Python dictionaries and lists, which makes it easy to learn. Python has a built in json module that converts between your Python objects and JSON text. Converting a Python object to JSON text is called serializing, and the opposite is called deserializing.

In this chapter you will convert data in both directions, save it to files, make the output easy to read, and learn which Python values JSON cannot handle.

JSON and Python types

A JSON document is built from objects (written with curly braces), arrays (square brackets), strings, numbers, true, false and null. Python maps them in a natural way. Note that JSON strings must use double quotes, and the words true, false and null are written in lower case.

PythonJSON
dictobject
list, tuplearray
strstring
int, floatnumber
True / Falsetrue / false
Nonenull

Python to JSON text with dumps

The function json.dumps() (the s means string) turns a Python object into JSON text. The result is a normal Python string. Look closely at the output below: the tuple became an array, True became true, and None became null.

Example 1: dumps
import json

person = {"name": "Asha", "age": 21, "skills": ("python", "sql"), "active": True, "manager": None}
text = json.dumps(person)
print(text)
print(type(text).__name__)
{"name": "Asha", "age": 21, "skills": ["python", "sql"], "active": true, "manager": null} str

JSON text to Python with loads

The function json.loads() does the reverse. It reads a string that holds JSON and gives you the matching Python object. Because JSON has no tuples, the array comes back as a list. This means a round trip can change a tuple into a list.

Example 2: loads
import json

text = '{"name": "Asha", "skills": ["python", "sql"], "active": true, "manager": null}'
data = json.loads(text)
print(data["name"])
print(data["skills"][1])
print(data["active"], data["manager"])
print(type(data).__name__)
Asha sql True None dict

Saving to and loading from files

For files there are two sister functions without the s: json.dump(obj, file) writes straight to an open file, and json.load(file) reads from one. They do the same work as dumps and loads but save you from handling the string yourself. The example below uses indent=2 to make the saved file easy for humans to read, and sort_keys=True to write the keys in alphabetical order.

Example 3: dump and load
import json

settings = {"theme": "dark", "font_size": 14, "recent": ["a.txt", "b.txt"]}

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

with open("settings.json", encoding="utf-8") as f:
    print(f.read())

with open("settings.json", encoding="utf-8") as f:
    loaded = json.load(f)
print(loaded == settings)
{ "font_size": 14, "recent": [ "a.txt", "b.txt" ], "theme": "dark" } True
Easy way to remember: dump and load work with files, dumps and loads work with strings.

Nested data

Real JSON is usually nested: lists inside dictionaries inside lists. After loading, you reach the values with normal indexing. Loops work as usual too, so you can total prices or search for a name just as you would with ordinary Python data.

Example 4: Working with nested data
import json

text = '''
{"shop": "Corner Store",
 "items": [
   {"name": "pen", "price": 10, "qty": 3},
   {"name": "book", "price": 45, "qty": 2}
 ]}
'''
data = json.loads(text)
total = 0
for item in data["items"]:
    total += item["price"] * item["qty"]
print(data["shop"], total)
Corner Store 120

Errors and limits

If the text is not valid JSON, for example when it uses single quotes, loads raises json.JSONDecodeError, which is a kind of ValueError. In the other direction, dumps raises TypeError for objects that JSON does not know, such as sets and custom class objects. You can fix this by converting the value first, or by giving a default function that tells json how to convert it. Also remember that JSON object keys are always strings, so the integer key 1 comes back as "1".

Example 5: Handling problems
import json

try:
    json.loads("{'a': 1}")
except json.JSONDecodeError:
    print("bad json")

try:
    json.dumps({"tags": {1, 2}})
except TypeError:
    print("set not allowed")

print(json.dumps({"tags": {1, 2}}, default=sorted))
print(json.loads(json.dumps({1: "one"})))
bad json set not allowed {"tags": [1, 2]} {'1': 'one'}

The default=sorted argument is called only for values that json cannot handle. Here it turns the set into a sorted list, which JSON can store. By default, non-English letters are written as escape codes like \u0905. Pass ensure_ascii=False to keep the real characters, and open the file with UTF-8.

When to choose JSON

JSON is a good choice when your data is made of simple things: text, numbers, lists and dictionaries. It is easy to read, easy to edit by hand, and almost every programming language can read it. It is not the best choice for very large tables, where CSV or a database is more efficient, and it cannot store complex Python objects such as functions or open files. If you need to save your own class objects, a common habit is to convert them to a dictionary first, save that, and rebuild the object after loading.

Another practical point is safety. Loading JSON never runs code, unlike some other formats, so reading a JSON file from a stranger is safe in that sense. You should still check that the keys you expect are present, because the file may be missing data or may have been edited by hand.

Python syntax

Syntax
text = json.dumps(obj, indent=2, sort_keys=True)
Syntax
obj = json.loads(text)
Syntax
with open("f.json", "w", encoding="utf-8") as f:
    json.dump(obj, f, indent=2)
Syntax
with open("f.json", encoding="utf-8") as f:
    obj = json.load(f)

Real-world applications

  • Saving program settings and user preferences.
  • Reading data from web APIs, which usually answer in JSON.
  • Storing small data sets such as to-do lists or game scores.
  • Exchanging data between programs written in different languages.

Common mistakes

Mistake: Mixing up dump/load with dumps/loads.
Fix: The functions with s work with strings. The ones without s work with file objects.
Mistake: Writing JSON by hand with single quotes or a trailing comma.
Fix: JSON needs double quotes and no trailing commas. Let json.dumps create the text.
Mistake: Expecting a tuple or an integer key to survive a round trip.
Fix: Tuples come back as lists and keys come back as strings. Convert them again if needed.
Mistake: Trying to dump a set, a date or a custom object.
Fix: Convert it to a list, string or dict first, or provide a default function.
Mistake: Opening the file in the wrong mode, such as reading with mode w.
Fix: Use "w" for dump and "r" (the default) for load.

Important tips

  • Use indent=2 while you develop, so the output is easy to read.
  • Use sort_keys=True when you want stable output that is easy to compare.
  • Use .get() on loaded dictionaries when a key may be missing.
  • Pass ensure_ascii=False to keep non-English text readable.

Key points summary

  • JSON is a text format for objects, arrays, strings, numbers, true, false and null.
  • dumps and loads work with strings; dump and load work with files.
  • Tuples become lists and dictionary keys become strings.
  • Invalid text raises json.JSONDecodeError.
  • indent and sort_keys make output readable and stable.

Exam and interview points

  • json is a standard library module.
  • dumps returns str; loads accepts str.
  • None maps to null and True maps to true.
  • json.JSONDecodeError is a subclass of ValueError.

Quick revision

  • import json
  • dumps/loads: strings.
  • dump/load: files.
  • indent=2 for pretty output.
  • tuple becomes list; keys become strings.

Frequently asked questions

What is the difference between json.dump and json.dumps?

dump writes to a file object. dumps returns the JSON text as a string.

Is JSON the same as a Python dictionary?

No. It is a text format that looks similar. Python dictionaries are objects in memory and can hold things JSON cannot.

Why does my integer key become a string?

JSON allows only strings as object keys. Python converts them when writing.

How can I store a date?

Convert it to a string, for example with isoformat(), and convert it back after loading.

Practise this chapter

17 practice questions Take the chapter quiz

Related chapters