To be able to generate a checkboxes, I need to convert pandas DataFrame to a JSON format.
First, I have a pandas Dataframe:
cast | title | type |
---|---|---|
Daniel Craig | Sky Fall | Movie |
Ahmed Bakare | Bad Habits | Music Video |
Leonardo Dicaprio | Titanic | Movie |
Judi Dench | Sky Fall | Movie |
Kate Winslet | Titanic | Movie |
Emily Ratajkowski | Blurred Lines | Music Video |
Elle Evans | Blurred Lines | Music Video |
I would like to convert it same like the format below:
{
"Movie": {
"label": "Movie",
"children": {
"Sky Fall": {
"label": "Sky Fall",
"children": {
"Daniel Craig": {
"label": "Daniel Craig"
},
"Judi Dench": {
"label": "Judi Dench"
}
}
},
"Titanic": {
"label": "Titanic",
"children": {
"Leonardo Dicaprio": {
"label": "Leonardo Dicaprio"
},
"Kate Winslet": {
"label": "Kate Winslet"
}
}
}
}
},
"Music Video": {
"label": "Music Video",
"children": {
"Bad Habits": {
"label": "Bad Habits",
"children": {
"Ahmed Bakare": {
"label": "Ahmed Bakare"
}
}
},
"Blurred Lines": {
"label": "Blurred Lines",
"children": {
"Emily Ratajkowski": {
"label": "Emily Ratajkowski"
},
"Elle Evans": {
"label": "Elle Evans"
}
}
}
}
}
};
My current approach is:
menu = []
groupDict = df.groupby('type').apply(lambda g: g.drop('type', axis=1).to_dict(orient='records')).to_dict()
for key, value in groupDict.items():
menu.append(dict(type=key,children=str(value)))
However, the result doest not come as I expected.
[{'type': 'Movie',
'children': "[{'cast': 'Daniel Craig', 'title': 'Sky Fall'}, {'cast': 'Leonardo Dicaprio', 'title': 'Titanic'}, {'cast': 'Judi Dench', 'title': 'Sky Fall'}, {'cast': 'Kate Winslet', 'title': 'Titanic'}]"},
{'type': 'Music Video',
'children': "[{'cast': 'Ahmed Bakare', 'title': 'Bad Habits'}, {'cast': 'Emily Ratajkowski', 'title': 'Blurred Lines'}, {'cast': 'Elle Evans', 'title': 'Blurred Lines'}]"}]