To write a json to a file, use the built-in json.dump(obj, file) method that serializes a Python object to a JSON-formatted file. It writes directly to an open file object.
import json
data = {
"title": "HP and Half blood Prince",
"author": "JK Rowling",
"pages": 544,
"genres": "fantasy",
"rating": 4.7
}
with open('dir/data.json', 'w') as file:
json.dump(data, file, indent=4)
print("Data written to file successfully.")
# Output: Data written to file successfully.
In this code, we directly open the file in write mode (‘w’) and dump the json data into a file, and after the file is written, it is closed automatically.
We wrote the file in the “dir” folder, as attached in the above screenshot, and we also attached a screenshot of the data.json file. For better readability and pretty printing, we passed an indent of 4.
Reading JSON from a file
You can use the built-in json.load() method to deserialize JSON from a file to a Python object.
Open the file in read mode (‘r’), load it, and read the content.
import json
with open('dir/data.json', 'r') as file:
loaded_data = json.load(file)
print(loaded_data)
# Output:
# {'title': 'HP and Half blood Prince', 'author': 'JK Rowling', 'pages': 544, 'genres': 'fantasy', 'rating': 4.7}
Empty file
If the JSON file you are trying to read is empty, it throws json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0).
import json
with open('dir/data.json', 'r') as file:
loaded_data = json.load(file)
print(loaded_data)
# json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
To fix this type of error or prevent it from occurring, always wrap in try-except for robustness.
import json
try:
with open('dir/data.json', 'r') as file:
json.load(file)
except json.JSONDecodeError:
print("Empty or invalid JSON")
# Output: Empty or invalid JSON
That’s all!


