Contents
- Introduction
- Example 1: Write JSON [Object] to File
- Example 2: Write JSON [List of Object] to File
- Summary
Python Write JSON to File
You can convert any Python object to a JSON string and write JSON to File using json.dumps[] function and file.write[] function respectively.
Following is a step by step process to write JSON to file.
- Prepare JSON string by converting a Python Object to JSON string using json.dumps[] function.
- Create a JSON file using open[filename, w] function. We are opening file in write mode.
- Use file.write[text] to write JSON content prepared in step 1 to the file created in step 2.
- Close the JSON file.
Example 1: Write JSON [Object] to File
In this example, we will convert or dump a Python Dictionary to JSON String, and write this JSON string to a file named data.json.
Python Program
Output
Run the above program, and data.json will be created in the working directory.
data.json
{"a": 54, "b": 87}Example 2: Write JSON [List of Object] to File
In this example, we will convert or dump Python List of Dictionaries to JSON string, and write this JSON string to file named data.json.
Python Program
Output
Run the above program, and data.json will be created in the working directory.
data.json
[{"a": 54, "b": 87}, {"c": 81, "d": 63}, {"e": 17, "f": 39}]Summary
In this tutorial of Python Examples, we learned how to write JSON to File, using step by step process and detailed example programs.
Related Tutorials
- Python CSV to JSON
- Python Dictionary to JSON
- Python Create JSON
- Python List to JSON
- Python JSON to List
- Python Parse JSON String
- Python JSON to Dictionary
- Python Read JSON File