I have this JSON object which has structure as follows (the json object was extracted from pandas dataframe using to_json(orient="records")
)
data = [{'month': 'Jan','date': '18','activity': 'cycling','duration': 3},
{'month': 'Jan', 'date': '18','activity': 'reading', 'duration': 3.0},
{'month': 'Jan', 'date': '19', 'activity': 'scripting', 'duration': 19.5},
{'month': 'Feb','date': '18', 'activity': 'work', 'duration': 22.0 },
{'month': 'Feb', 'date': '19', 'activity': 'cooking','duration': 0.7},
{'month': 'March', 'date': '16', 'activity': 'hiking', 'duration': 8.0}]
Am trying to group by two fields month
and date
Expected result:
data = [{
"month": "Jan",
"details": [{
"date": "18",
"effort": [{
"activity": "cycling",
"duration": 3
}, {
"activity": "reading",
"duration": 3.0
}]
}, {
"date": "19",
"effort": [{
"activity": "scripting",
"duration": 19.5
}]
}]
}, {
"month": "Feb",
"details": [{
"date": "18",
"effort": [{
"activity": "work",
"duration": 22.0
}]
}, {
"date": "19",
"effort": [{
"activity": "cooking",
"duration": 0.7
}]
}]
}, {
"month": "March",
"details": [{
"date": "16",
"effort": [{
"activity": "hiking",
"duration": 8.0
}]
}]
}]
I tried having the data as python dictionary which is extracted from pandas dataframe using to_dict(orient="records")
list_ = []
for item in dict_:
list_.append({"month" : item["month"],
"details":
[{
"date" : item["date"],
"efforts" :
[{
"activity" : item["activity"],
"duration": item["duration"]
}]
}]
})
json.dumps(list_)
and the output i got is
[{
"month": "Jan",
"details": [{
"date": "18",
"efforts": [{
"duration": 3,
"activity": "cycling"
}]
}]
}, {
"month": "Jan",
"details": [{
"date": "18",
"efforts": [{
"duration": 3.0,
"activity": "reading"
}]
}]
}, {
"month": "Jan",
"details": [{
"date": "19",
"efforts": [{
"duration": 19.5,
"activity": "scripting"
}]
}]
}, {
"month": "Feb",
"details": [{
"date": "18",
"efforts": [{
"duration": 22.0,
"activity": "work"
}]
}]
}, {
"month": "Feb",
"details": [{
"date": "19",
"efforts": [{
"duration": 0.7,
"activity": "cooking"
}]
}]
}, {
"month": "March",
"details": [{
"date": "16",
"efforts": [{
"duration": 8.0,
"activity": "hiking"
}]
}]
}]
am not handling the concatenation of values to the existing fields.
Tried using python as well as java-script, do you guys have any advice or solution to the problem? Thanks