I have this code that allows me to create a JSON file from a list, creates the list, checks that the elements don't repeat, and then creates the JSON file.
import json
res = []
seen = set()
def add_entry(res, id, tf1, tf2, tf3):
# check if in seen set
if (id, tf1, tf2, tf3) in seen:
return res
# add to seen set
seen.add(tuple([id, tf1, tf2, tf3]))
# append to results list
res.append({'metrica': id, 'ft1': tf1, 'tf2': tf2, 'tf3': tf3})
return res
args = ['ext:tech.DB2', '40,023', '168,481', '15,55']
res = add_entry(res, *args)
args = ['ext:bim.DB2', '25,02', '18,81', '5,35']
res = add_entry(res, *args)
def write_to_json(lst, fn):
with open(fn, 'a', encoding='utf-8') as file:
for item in lst:
x = json.dumps(item, indent=4)
file.write(x + '\n')
#export to JSON
write_to_json(res, 'elements.json')
Only the JSON file is not a real JSON file:
{
"metrica": "ext:bim.DB2",
"ft1": "40,023",
"tf2": "168,481",
"tf3": "15,55"
}
{
"metrica": "ext:bim.DB2",
"ft1": "25,02",
"tf2": "18,81",
"tf3": "5,35"
}
How can I make it like this:
{"data":[{
"metrica": "ext:bim.DB2",
"ft1": "40,023",
"tf2": "168,481",
"tf3": "15,55"
},
{
"metrica": "ext:bim.DB2",
"ft1": "25,02",
"tf2": "18,81",
"tf3": "5,35"
}]}
the json file I generate it in the code and then dynamically I need to pass it to another function, even if I wanted to, I could not change the values manually, also because I would have more than 900 elements to change, how can I do it dynamically?
json.dump({"data": lst}, file, indent=4)should ideally be enough.