Beginner Level
Intermediate Level
Advanced Level
Introduction
JSON stands for JavaScript Object Notation, and it is a lightweight data interchange format that is easy to read and write. In this tutorial, we will explore how to write data to a JSON file in Python. We will begin by defining what a JSON file is and why it is useful. Then, we will walk through the steps required to create, write, and save data to a JSON file using Python.
Table of Contents :
- Introduction to Writing JSON Files
- json.dump() Method
- json.dumps() Method
- Creating and Writing JSON Data
- Writing Pretty JSON Data
- Appending to an Existing JSON File
- Handling Errors when Writing JSON Files
Introduction to Writing JSON Files :
- JSON files are commonly used to store and transfer data between different programming languages.
- Python provides a
json
module for working with JSON data. - We can use this module to write data to a JSON file in Python.
json.dump() Method :
- To write data to a JSON file, you will need to use the
json.dump()
method. - This method takes two arguments:
- The data that you want to write to the file. This can be a Python dictionary, list, or other data type.
- The file object that you want to write the data to. This can be created using the open() function.
- Here is a simple example of how to write data to a JSON file:
- Code Sample :
import json
data = {'name': 'John Doe', 'age': 42, 'city': 'New York'}
with open('data.json', 'w') as f:
json.dump(data, f)
# In the example above,
# we first import the json module.
# We then create a Python dictionary with some data.
# We then open a file called data.json in write mode.
# We then use the json.dump() method to write the data to the file.
json.dumps() Method :
- You can also use the
json.dumps()
method to write data to a file. - This method takes only one argument - the data that you want to write to the file.
- It returns a JSON-encoded string.
- Here is an example of how to use the
json.dumps()
method: - Code Sample :
import json
data = {'name': 'John Doe', 'age': 42, 'city': 'New York'}
with open('data.json', 'w') as f:
f.write(json.dumps(data))
Creating and Writing JSON Data :
- To write a JSON file, first create a Python object containing the data you want to write.
- Use the
json
module to convert the Python object to a JSON string. - Then, write the JSON string to a file using Python's file handling methods.
- Code Sample :
import json
data = {
"name": "John",
"age": 30,
"isStudent": True,
"subjects": ["English", "Maths", "Science"],
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zip": "10001"
}
}
json_data = json.dumps(data)
with open("example.json", "w") as f:
f.write(json_data)
Writing Pretty JSON Data :
- JSON data can be written in a human-readable format using the
indent
parameter of thejson.dumps()
method. - Code Sample :
import json
data = {
"name": "John",
"age": 30,
"isStudent": True,
"subjects": ["English", "Maths", "Science"],
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zip": "10001"
}
}
json_data = json.dumps(data, indent=4)
with open("example.json", "w") as f:
f.write(json_data)
Appending to an Existing JSON File
- To append data to an existing JSON file, first read the file's current data.
- Then, update the data and write it back to the file.
- Code Sample :
import json
with open("example.json", "r") as f:
data = json.load(f)
data["grades"] = [90, 85, 95]
with open("example.json", "w") as f:
json.dump(data, f, indent=4)
Handling Errors when Writing JSON Files
- Errors can occur when writing and formatting JSON files in Python, such as invalid syntax or missing keys.
- You can use error handling to gracefully handle these errors.
- Use a try-except statement with the
JSONEncodeError
exception to handle encoding errors. - Code Sample :
import json
data = {
"name": "John",
"age": 30,
"isStudent": True,
"subjects": ["English", "Maths", "Science"],
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY"
}
}
try:
json_data = json.dumps(data)
except json.JSONEncodeError as e:
print(f"JSON encoding error: {e}")
else:
with open("example.json", "w") as f:
f.write(json_data)
Prev. Tutorial : Reading json file
Next Tutorial : Append data to json file