Here are 3 ways to write data to a json file using Python:
(1) Single dictionary to a json file:
import json data = { "product": "Computer", "price": 1300, "brand": "A" } file_path = r"path to save the json file\file_name.json" with open(file_path, "w") as file: json.dump(data, file, indent=4)
Where:
- “w” stands for a write mode
- json.dump() writes the data to a json file with a specified indentation for readability
The resulted json file:
{
"product": "Computer",
"price": 1300,
"brand": "A"
}
(2) Single dictionary of keys, and values consisting of lists of multiple entries:
import json data = { "product": ["Computer", "Printer", "Tablet"], "price": [1300, 150, 400], "brand": ["A", "B", "C"] } file_path = r"path to save the json file\file_name.json" with open(file_path, "w") as file: json.dump(data, file, indent=4)
The result:
{
"product": [
"Computer",
"Printer",
"Tablet"
],
"price": [
1300,
150,
400
],
"brand": [
"A",
"B",
"C"
]
}
(3) List of dictionaries containing multiple entries:
import json data = [ { "product": "Computer", "price": 1300, "brand": "A" }, { "product": "Printer", "price": 150, "brand": "B" }, { "product": "Tablet", "price": 400, "brand": "C" } ] file_path = r"path to save the json file\file_name.json" with open(file_path, "w") as file: json.dump(data, file, indent=4)
The result:
[
{
"product": "Computer",
"price": 1300,
"brand": "A"
},
{
"product": "Printer",
"price": 150,
"brand": "B"
},
{
"product": "Tablet",
"price": 400,
"brand": "C"
}
]