Reading and Writing JSON to a File in Python

JSON (JavaScript Object Notation) is a lightweight data interchange format that’s easy for humans to read and write, and easy for machines to parse and generate.
Python provides excellent support for working with JSON data through its built-in json module.

Foreword

For more details, check out the official Python documentation on the json module.

Writing JSON to a File

Let’s start with writing JSON data to a file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import json

# Your Python dictionary
data = {
"name": "John Doe",
"age": 30,
"city": "New York",
"languages": ["Python", "JavaScript", "Go"],
"is_employee": True,
"details": {
"title": "Developer",
"experience": 5
}
}

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

The indent=4 parameter makes the output file nicely formatted with 4-space indentation.

Reading JSON from a File

Reading JSON data from a file is just as straightforward:

1
2
3
4
5
6
7
8
9
import json

# Read from a file
with open("data.json", "r") as file:
loaded_data = json.load(file)

# Now you can work with the loaded data
print(loaded_data["name"]) # Output: John Doe
print(loaded_data["languages"][0]) # Output: Python

Error Handling

It’s good practice to include error handling when working with files:

1
2
3
4
5
6
7
8
9
import json

try:
with open("data.json", "r") as file:
data = json.load(file)
except FileNotFoundError:
print("The file was not found.")
except json.JSONDecodeError:
print("The file does not contain valid JSON.")

Working with JSON Strings

Sometimes you might need to convert between JSON strings and Python objects:

1
2
3
4
5
6
7
import json

# Convert Python object to JSON string
json_string = json.dumps(data, indent=4)

# Convert JSON string back to Python object
python_object = json.loads(json_string)

Preserving Order

By default, Python dictionaries preserve the insertion order (since Python 3.7). If you’re using an older version, you can use collections.OrderedDict:

1
2
3
4
5
6
7
8
9
10
11
import json
from collections import OrderedDict

ordered_data = OrderedDict([
("name", "John Doe"),
("age", 30),
("city", "New York")
])

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

Handling Special Data Types

JSON has limited data types. To handle Python-specific types like dates, you can create custom JSON encoders:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import json
import datetime

class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.isoformat()
return super().default(obj)

data_with_date = {
"name": "Event",
"date": datetime.datetime.now()
}

with open("event.json", "w") as file:
json.dump(data_with_date, file, cls=DateTimeEncoder, indent=4)

Reading and Writing JSON to a File in Python
https://www.hardyhu.cn/2023/04/29/Reading-and-Writing-JSON-to-a-File-in-Python/
Author
John Doe
Posted on
April 29, 2023
Licensed under