How to Write JSON File in Python: Simple Guide
To write a JSON file in Python, use the
json.dump() function from the json module. Open a file in write mode, then pass your Python data and the file object to json.dump() to save the data as JSON.Syntax
The basic syntax to write JSON data to a file in Python is:
import json: Imports the JSON module.with open('filename.json', 'w') as file:: Opens a file in write mode.json.dump(data, file): Writes the Python data to the file in JSON format.
python
import json data = {} with open('data.json', 'w') as file: json.dump(data, file)
Example
This example shows how to write a Python dictionary to a JSON file named data.json. It demonstrates opening the file, writing the JSON, and closing the file automatically.
python
import json # Python dictionary to save person = { "name": "Alice", "age": 30, "city": "New York" } # Write JSON file with open('data.json', 'w') as file: json.dump(person, file)
Common Pitfalls
Common mistakes when writing JSON files include:
- Not opening the file in write mode (
'w'), which causes errors. - Trying to write non-serializable Python objects like sets or custom classes without converting them.
- Forgetting to import the
jsonmodule.
Here is an example of a wrong and right way:
python
# Wrong: opening file in read mode import json person = {"name": "Bob"} try: with open('data.json', 'r') as file: json.dump(person, file) # This will raise an error except Exception as e: print(f"Error: {e}") # Right: open file in write mode with open('data.json', 'w') as file: json.dump(person, file)
Output
Error: not writable
Quick Reference
Tips for writing JSON files in Python:
- Always use
with open(filename, 'w')to safely open files. - Use
json.dump()to write Python data to JSON format. - Ensure data is JSON serializable (e.g., dict, list, str, int).
- Use
indentparameter injson.dump()for readable formatting.
python
import json person = {"name": "Eve", "age": 25} with open('pretty.json', 'w') as file: json.dump(person, file, indent=4)
Key Takeaways
Use the json module's dump() function to write Python data to a JSON file.
Always open the file in write mode ('w') before writing JSON data.
Ensure your Python data is JSON serializable to avoid errors.
Use the with statement to handle files safely and automatically close them.
Add indent parameter in json.dump() for readable JSON formatting.