I want to convert my dataframe to nested JSON so that I can use it to build my Mobile App. I need to make it nested. Level 0 will be brand. Level 1 will be model. Level 2 will be year. Level 3 will be rest of it. I have 6700 rows and 43 columns. And my dataframe looks like this. How to make it ?
Asked
Active
Viewed 36 times
0
-
Please post text and not images so that others can reproduce. – Serge Ballesta May 19 '20 at 13:02
-
I don't know how do i do that. Like other persons who post it in grey back ground with small text size. – Fatih Can May 19 '20 at 13:08
-
From the *About* page of pandas tag: See: [How to make good reproducible pandas examples](https://stackoverflow.com/q/20109391/3545273). Please *read* and use it. Another source of information is [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) from the Help Center, specifically the page on [code formatting](https://stackoverflow.com/editing-help#code). Docs are not to be ignored... – Serge Ballesta May 19 '20 at 13:32
1 Answers
2
You could just do it by hand with nested dict comprehensions:
data = {brand: {model: {year: df.loc[(df['brand']==brand)&(df['model']==model)
&(df['year']==year)].drop(
columns=['brand', 'model', 'year']
).to_dict(orient='list') for year in
df.loc[(df['brand']==brand)&(df['model']==model), 'year']
.unique()} for model in df.loc[(df['brand']==brand),
'model']
.unique()} for brand in df['brand'].unique()}
jsonstring = json.dumps(data)

Serge Ballesta
- 143,923
- 11
- 122
- 252
-
I'm really thankful for your help man. I appreciate it. My last question is , it holds data at last level like " AC heater 0: x " . X here is an float or integer but there are zeros on every line. Is that normal ? @Serge Ballesta – Fatih Can May 19 '20 at 15:39