Apr-02-2025, 09:01 PM
(This post was last modified: Apr-02-2025, 09:01 PM by deanhystad.)
You do not build a json file. You create a python object and use json.dump(obj, file) to create a json file.
This is what a the json file looks like for the list in your post.
[{"id": 1, "name": "Cole Volk", "fitness": {"height": 130, "weight": 60}}, {"name": "Mark Reg", "fitness": {"height": 130, "weight": 60}}, {"id": 2, "name": "Faye Raker", "fitness": {"height": 130, "weight": 60}}]
I created it like this:
1 Retrieve the records from the database.
2 Put the records in a list.
3 Open a file for writing.
4 Dump the list to the file.
You can use indent in the dump command to make the file prettier, but the purpose of json is portable storage and retrieval. json is not a human friendly presentation format.
This is a program that reads the json file and prints the list.
This is what a the json file looks like for the list in your post.
[{"id": 1, "name": "Cole Volk", "fitness": {"height": 130, "weight": 60}}, {"name": "Mark Reg", "fitness": {"height": 130, "weight": 60}}, {"id": 2, "name": "Faye Raker", "fitness": {"height": 130, "weight": 60}}]
I created it like this:
import json # This is not json. This is a list of dictionaries. data = [ { "id": 1, "name": "Cole Volk", "fitness": {"height": 130, "weight": 60}, }, {"name": "Mark Reg", "fitness": {"height": 130, "weight": 60}}, { "id": 2, "name": "Faye Raker", "fitness": {"height": 130, "weight": 60}, }, ] with open("test.json", "w") as file: data = json.dump(data, file) # This writes data to file using json syntax.If you had some records from a database that you want to put in a json file:
1 Retrieve the records from the database.
2 Put the records in a list.
3 Open a file for writing.
4 Dump the list to the file.
You can use indent in the dump command to make the file prettier, but the purpose of json is portable storage and retrieval. json is not a human friendly presentation format.
This is a program that reads the json file and prints the list.
import json with open("test.json", "r") as file: data = json.load(file) print(data)
Output:[{'id': 1, 'name': 'Cole Volk', 'fitness': {'height': 130, 'weight': 60}}, {'name': 'Mark Reg', 'fitness': {'height': 130, 'weight': 60}}, {'id': 2, 'name': 'Faye Raker', 'fitness': {'height': 130, 'weight': 60}}]
To make it pretty I can use json.import json with open("test.json", "r") as file: data = json.load(file) print(json.dumps(data, indent=4))
Output:[
{
"id": 1,
"name": "Cole Volk",
"fitness": {
"height": 130,
"weight": 60
}
},
{
"name": "Mark Reg",
"fitness": {
"height": 130,
"weight": 60
}
},
{
"id": 2,
"name": "Faye Raker",
"fitness": {
"height": 130,
"weight": 60
}
}
]
json.dumps(obj) is like json.dump(obj, file) except it produces a string instead of writing to a file. There is a corresponding json.loads(string) that is similar to json.load(file).