I am using pandas "to_json" option to generate some JSON files after filtering DF. The output of these comes as below:
[{"time":1677287760000,"x":0.001,"y":0.001,"z":0.0},{"time":1677632400000,"x":0.0,"y":0.0,"z":0.0},{"time":1677636000000,"x":0.0,"y":0.0,"z":0.0},{"time":1677639600000,"x":0.0,"y":0.0,"z":0.0}]
and
[{"dt":20,"count":6},{"dt":23,"count":9},{"dt":11,"count":7},{"dt":2,"count":16},{"dt":17,"count":1},{"dt":20,"count":6}]
I am looking for options to create a JSON file in python which will hold both as below:
{
"StatusTimes": [
{
"time": 1677287760000,
"x": 0.001,
"y": 0.001,
"z": 0
},
{
"time": 1677632400000,
"x": 0,
"y": 0,
"z": 0
},
{
"time": 1677636000000,
"x": 0,
"y": 0,
"z": 0
},
{
"time": 1677639600000,
"x": 0,
"y": 0,
"z": 0
}
],
"DtCount": [
{
"dt": 20,
"count": 6
},
{
"dt": 23,
"count": 9
},
{
"dt": 11,
"count": 7
},
{
"dt": 2,
"count": 16
},
{
"dt": 17,
"count": 1
},
{
"dt": 20,
"count": 6
}
]
}
Tried json dumps and then update to get errors. I was thinking to create a JSON object and then update the value as needed. i.e to start with
{
"StatusTimes": [],
"DtCount": []
}
Adding a name to the specific inner JSON object also didn’t work. Appreciate the help here
2
Answers
I think you might want to use the
to_dict
function instead: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_dict.html#pandas-dataframe-to-dictExample:
If you want the beautified json:
For creating a json file you can create a dictionary with the keys "StatusTimes". Then you can use json.dumps() to convert the dictionary into a JSON formatted string. This is example:
This will create a JSON file named output.json in your current directory with the desired structure.