
409 views
Save json File in Python
The save data as a JSON file in Python, you can use the json module, which provides methods for encoding Python data structures into JSON format and writing them to a file. Here’s a step-by-step guide:
- Import the
jsonmodule:
Python
import json- Create a Python data structure (e.g., a dictionary or a list) that you want to save as a JSON file.
Python
data = {
"name": "John",
"age": 30,
"city": "New York"
}- Specify the file path where you want to save the JSON data. Make sure to include the file extension “.json”.
Python
file_path = "data.json"- Open the file in write mode (
"w") using awithstatement, and use thejson.dump()function to write the data to the file.
Python
with open(file_path, "w") as json_file:
json.dump(data, json_file)Here’s the complete code:
Python
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
file_path = "data.json"
with open(file_path, "w") as json_file:
json.dump(data, json_file)After running this code, you will have a JSON file named “data.json” in your current working directory with the contents of the data dictionary.
You can also use the json.dumps() function to convert a Python data structure to a JSON-formatted string, which you can then save to a file manually:
Python
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_string = json.dumps(data)
file_path = "data.json"
with open(file_path, "w") as json_file:
json_file.write(json_string)This code will achieve the same result, with the data saved in “data.json.”