Python Working with JSON Files

In the last lesson, we learned about Python Working with CSV Files. After learning about CSV files, let us learn about JSON files in Python. JSON means “JavaScript Object Notation.” It is a very common format for storing and exchanging data.

In this tutorial, we will learn how to read JSON files, write JSON files, and convert between JSON and Python objects.

What Is a JSON File?

A JSON file is a text file that stores data in a structured way. It looks a lot like Python dictionaries and lists.

Here is an example:

{
"name": "Alex",
"age": 25,
"city": "London",
"courses": ["Math", "Physics", "Chemistry"]
}

JSON is used everywhere. APIs return JSON. Config files use JSON. Data is often stored as JSON.

Why Use JSON Files in Python?

JSON is easy to read. It is easy to write. And it works with almost every programming language. Python can read and write JSON easily.

That is why it is so popular.

The json Module in Python

Python has a built-in module called json. We import it and use its functions.

import json

Now we can use json.load(), json.dump(), json.loads(), and json.dumps().

How to Read a JSON File in Python

Let’s say we have a file called person.json:

{
"name": "Alex",
"age": 25,
"city": "London"
}

We can read it like this:

import json
with open("person.json", "r") as file:
data = json.load(file)
print(data)

Output

{'name': 'Alex', 'age': 25, 'city': 'London'}

Now data is a Python dictionary. We can access values by key.

print(data["name"])
print(data["age"])

Output

text Alex 25

That is how we read JSON. It becomes a Python dictionary automatically.

How to Write a JSON File in Python

To write a JSON file, we use json.dump().

import json
person = {
"name": "Alex",
"age": 25,
"city": "London"
}
with open("person.json", "w") as file:
json.dump(person, file)

After running this, person.json contains:

{ "name": "Alex", "age": 25, "city": "London" }

That works. But it is all on one line. If we want it to be readable, we use indent.

with open("person.json", "w") as file:
json.dump(person, file, indent=4)

Now the file looks like this:

{
"name": "Alex",
"age": 25,
"city": "London"
}

That is much nicer.

JSON vs Python Types

JSON and Python have similar types. But not exactly the same.

JSONPython
objectdict
arraylist
stringstr
numberint or float
trueTrue
falseFalse
nullNone

So when we read JSON, it becomes Python types. When we write JSON, Python types become JSON.

How to Read JSON from a String in Python

Sometimes we have JSON as a string. Not in a file. We can use json.loads() to parse it.

import json
json_string = '{"name": "Alex", "age": 25}'
data = json.loads(json_string)
print(data)

Output

{'name': 'Alex', 'age': 25}

The “s” in loads stands for “string.”

How to Write JSON to a String in Python

We can also convert a Python object to a JSON string using json.dumps().

import json
person = {"name": "Alex", "age": 25}
json_string = json.dumps(person)
print(json_string)

Output

{"name": "Alex", "age": 25}

Again, the “s” stands for “string.”

Python JSON Example – Reading a List of Students

Let’s read a JSON file of students and print their names.

import json
with open("students.json", "r") as file:
students = json.load(file)
for student in students:
print(f"{student['name']} is {student['age']} years old")

If students.json contains:

[
{ "name": "Alex", "age": 25 },
{ "name": "Sam", "age": 30 },
{ "name": "John", "age": 22 }
]

The output is:

Alex is 25 years old
Sam is 30 years old
John is 22 years old

That is a simple way to work with JSON data.

Another Example – Saving a List of Dictionaries to JSON

import json
people = [
{"name": "Alex", "age": 25, "city": "London"},
{"name": "Sam", "age": 30, "city": "Manchester"},
{"name": "John", "age": 22, "city": "Birmingham"}
]
with open("people.json", "w") as file:
json.dump(people, file, indent=4)
print("Data saved!")

The file people.json will contain:

[
{
"name": "Alex",
"age": 25,
"city": "London"
},
{
"name": "Sam",
"age": 30,
"city": "Manchester"
},
{
"name": "John",
"age": 22,
"city": "Birmingham"
}
]

That is clean and readable.

Common Mistakes When Working with JSON in Python

Mistake 1: Forgetting to import json

with open("data.json", "r") as file:
data = json.load(file)

This gives an error if we did not import json.

Fix:

import json

Mistake 2: Using the wrong function

  • json.load() reads from a file object.
  • json.loads() reads from a string.
  • json.dump() writes to a file object.
  • json.dumps() writes to a string.

Do not mix them up.

Mistake 3: Trying to write a non-serializable object

import json
data = {"date": datetime.datetime.now()}
with open("data.json", "w") as file:
json.dump(data, file)

Output

TypeError: Object of type datetime is not JSON serializable

Fix: Convert the object to a string or a serializable type first.

data = {"date": str(datetime.datetime.now())}

Mistake 4: Forgetting indent for readability

with open("data.json", "w") as file:
json.dump(data, file)

This writes everything on one line. If we want it readable, use indent.

with open("data.json", "w") as file:
json.dump(data, file, indent=4)

Next, we will learn Python File Paths, so our programs can find files reliably even when they live inside folders.