Python Write JSON to File
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.
Examples
1. Write JSON (Object) string 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
import json
aDict = {"a":54, "b":87}
jsonString = json.dumps(aDict)
jsonFile = open("data.json", "w")
jsonFile.write(jsonString)
jsonFile.close()
Output
Run the above program, and data.json will be created in the working directory.
data.json
{"a": 54, "b": 87}
2. Write JSON (list of objects) to a 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
import json
aList = [{"a":54, "b":87}, {"c":81, "d":63}, {"e":17, "f":39}]
jsonString = json.dumps(aList)
jsonFile = open("data.json", "w")
jsonFile.write(jsonString)
jsonFile.close()
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 Python JSON Tutorial, we learned how to write JSON to File, using step by step process and detailed example programs.