Create a Json-File in Python with for loop and write a variable in the Json-File

Viewed 44

I am pretty new to Json files. I want to create a Json file with 10 JSon objects. Each Object has a temperature, flow and pressure given by a Sensor. The values for each are stored in a variable. I can create the Json file but the variable is always handled like a string. To make it simple I've created a similar loop where every Json Object got only one entry, the variable stored as ID.

This is my try:

json_Daten2 = [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}]
for i in range(10):
    json_Daten2[i] = """
    {
        "ID": i,
    }
    """

And this is my result:

[
    "\n    {\n        \"ID\": i,\n    }\n    ",
    "\n    {\n        \"ID\": i,\n    }\n    ",
    "\n    {\n        \"ID\": i,\n    }\n    ",
    "\n    {\n        \"ID\": i,\n    }\n    ",
    "\n    {\n        \"ID\": i,\n    }\n    ",
    "\n    {\n        \"ID\": i,\n    }\n    ",
    "\n    {\n        \"ID\": i,\n    }\n    ",
    "\n    {\n        \"ID\": i,\n    }\n    ",
    "\n    {\n        \"ID\": i,\n    }\n    ",
    "\n    {\n        \"ID\": i,\n    }\n    "
]

Sorry if I've missed an similarly Boardentry but I am thankful for every hint or help!

Thanks in advance!

Max

2 Answers

That's because you used string. How about that:

for i in range(10):
    json_Daten2[i] = {"ID": i}

you dont need to do this man, python dumps json naturaly:

from json import dump,dumps
MY_DATA = [ 
    {'id':112,'tempeture':2.23},
    {'id':112,'tempeture':2.23}
]

#if you want in string mode
result = dumps(MY_DATA,ensure_ascii=False,indent=4)
print(result)

#if you want in file 
with open('teste.json','w') as arq:
    dump(MY_DATA,arq)
Related