i have a JSON file as follow:
{
"temperature": [
{
"ts": 1672753924545,
"value": "100"
}
],
"temperature c1": [
{
"ts": 1672753924545,
"value": "30.99036523512186"
}
],
"conductivite_c1": [
{
"ts": 1672753924545,
"value": "18.195760116755046"
}
],
"pression_c1": [
{
"ts": 1672753924545,
"value": "10.557751448931295"
}
],
"ph_c1": [
{
"ts": 1672753924545,
"value": "10.443975738053357"
}
],
"http": [
{
"ts": 1672753924545,
"value": "400"
}
]
}
this is my code :
import csv
import json
data = json.loads('{"temperature": [{"ts": 1672753924545, "value": "100"}], "temperature c1": [{"ts": 1672753924545, "value": "30.99036523512186"}], "conductivite_c1": [{"ts": 1672753924545, "value": "18.195760116755046"}], "pression_c1": [{"ts": 1672753924545, "value": "10.557751448931295"}], "ph_c1": [{"ts": 1672753924545, "value": "10.443975738053357"}], "http": [{"ts": 1672753924545, "value": "400"}]}')
with open('data.csv', 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=data.keys())
writer.writeheader()
for key in data:
for row in data[key]:
writer.writerow({key: row['value']})
i want to convert it to CSV with ts in rows ( not the same row ) and the keys are columns
but it gives me a weired format where all the keys in the same column and no ts
3
Answers
If you want each time new data.csv, just replace "a" in open(‘data2.csv’, ‘a’) to "w" and if you also need all csv files, you must generate new name for csv file
I would reformat your data
Here is a simple implementation:
Note that it will also add a new row if there is more than one timestamp for each field.