I am pretty new in Json-Files. I want to create a Json-File with 10 JSon Objects. Each Object has a temerature, flow and preasure 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 similary 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 simmilary Boardentry but I am thankfull for every hint or help! Thx in advance!
Max
CodePudding user response:
That's because you used string. How about that:
for i in range(10):
json_Daten2[i] = {"ID": i}
CodePudding user response:
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)