Home »
Python »
Python Articles
Writing JSON to a file in Python
By IncludeHelp Last updated : February 20, 2024
To write JSON to a file, you can use the combination of json.dumps() method and file handling in Python. The json.dumps() method converts a Python object to a JSON string, opens the file in "w" mode, and writes the JSON string to a file.
Syntax
Below is the code to write JSON to a file:
with open("sample_file.json", "w") as out:
json.dump(json_data, out)
Python program to write JSON to a file
This program writes a given JSON object to a file in Python.
# Code to write JSON to a file
# Importing json moduke
import json
# Python object to be written
json_data = {
"id": "101",
"name": "ALex",
"age": 21,
"phonenumber": "8818923409"
}
# Writing to a file
with open("sample_file.json", "w") as out:
json.dump(json_data, out)
Output
The output of the above program is:
File's data: sample_file.json
{"id": "101", "name": "ALex", "age": 21, "phonenumber": "8818923409"}
To understand the above program, you should have the basic knowledge of the following Python topics: