I would like to be able with Python to collect or reparse JSON using the first level key.
There is a JSON like this:
[{
"system": "test111",
"data": { "title": "SomeValue", "time": "2022-10-22T10:36:43.000000", "value": 0 }
},
{
"system": "test111",
"data": { "title": "SomeValue", "time": "2022-10-22T10:36:43.111111", "value": 11 }
},
{
"system": "test111",
"data": { "title": "SomeValue", "time": "2022-10-22T10:36:43.222222", "value": 22 }
},
{
"system": "test222",
"data": { "title": "SomeValue", "time": "2022-10-22T10:36:43.333333", "value": 33 }
},
{
"system": "test222",
"data": { "title": "SomeValue", "time": "2022-10-22T10:36:43.444444", "value": 44 }
},
{
"system": "test333",
"data": { "title": "SomeValue", "time": "2022-10-22T10:36:43.555555", "value": 55 }
},
{
"system": "test333",
"data": { "title": "SomeValue", "time": "2022-10-22T10:36:43.666666", "value": 66 }
},
{
"system": "test444",
"data": { "title": "SomeValue", "time": "2022-10-22T10:36:43.777777", "value": 77 }
},
{
"system": "test444",
"data": { "title": "SomeValue", "time": "2022-10-22T10:36:43.888888", "value": 88 }
},
{
"system": "test555",
"data": { "title": "SomeValue", "time": "2022-10-22T10:36:43.999999", "value": 99 }
}]
And I want to regenerate JSON like this:
[{
"system": "test111",
"data": [{ "title": "SomeValue", "time": "2022-10-22T10:36:43.000000", "value": 0 }, { "title": "SomeValue", "time": "2022-10-22T10:36:43.111111", "value": 11 }, { "title": "SomeValue", "time": "2022-10-22T10:36:43.222222", "value": 22 }]
},
{
"system": "test222",
"data": [{ "title": "SomeValue", "time": "2022-10-22T10:36:43.333333", "value": 33 }, { "title": "SomeValue", "time": "2022-10-22T10:36:43.444444", "value": 44 }]
},
{
"system": "test333",
"data": [{ "title": "SomeValue", "time": "2022-10-22T10:36:43.555555", "value": 55 }, { "title": "SomeValue", "time": "2022-10-22T10:36:43.666666", "value": 66 }]
},
{
"system": "test444",
"data": [{ "title": "SomeValue", "time": "2022-10-22T10:36:43.777777", "value": 77 }, { "title": "SomeValue", "time": "2022-10-22T10:36:43.888888", "value": 88 }]
},
{
"system": "test555",
"data": [{ "title": "SomeValue", "time": "2022-10-22T10:36:43.999999", "value": 99 }]
}]
In short, how to collect all system key values and group the results accordingly?
Thanks
2
Answers
You can use
json.loads()
to convert your JSON into a dictionaryThen a simple loop over the
system
key should allow you to regroup thedata
field into a list of dictionaries.You can convert the new dictionary you created back into a JSON file using
json.dumps()
You could make use of
groupby
and do something like this:Result: