简体   繁体   中英

How to create a nested json with key names in python?

I have the following data in a pandas dataframe. I want to group the data based on month, then type.

month   hour    Type    count
0   4   0   Bike    8
1   4   0   Pedelec 16
2   4   1   Bike    9
3   4   1   Pedelec 4
4   4   2   Bike    18
... ... ... ... ...
412 12  21  Pedelec 15
413 12  22  Bike    7
414 12  22  Pedelec 10
415 12  23  Bike    2
416 12  23  Pedelec 15

I want to convert this to a nested json with field names. The code I use to create a dictionary is this:

jsonfile=barchart.groupby(['month','Type'])[['hour','count']].apply(lambda x: x.to_dict('r')).reset_index(name='data').groupby('month')['Type','data'].apply(lambda x: x.set_index('Type')['data'].to_dict()).reset_index(name='data').groupby('month')['data'].apply(list).to_dict()

The output I get is in this format:

[{'month': 4,
  'values': [{'Bike': [{'hour': 0, 'count': 8},
     {'hour': 1, 'count': 9},
     {'hour': 2, 'count': 18},
     {'hour': 3, 'count': 2},
     {'hour': 4, 'count': 2},
 ...
     {'hour': 23, 'count': 14}],
    'Pedelec': [{'hour': 0, 'count': 16},
     {'hour': 1, 'count': 4},
     {'hour': 2, 'count': 12},
...
     {'hour': 23, 'count': 27}]}]},

Expected output:

[{'month': 4,
  'values': [{'Type': 'Bike': [{'hour': 0, 'count': 8},
     {'hour': 1, 'count': 9},

I used the following to create my deired format

jsonfile=barchart.groupby(['month','Type'])[['hour','count']].apply(lambda x: x.to_dict('r')).reset_index(name='data').groupby('month')['Type','data'].apply(lambda x: x.set_index('Type')['data'].to_dict()).reset_index(name='data').groupby('month')['data'].apply(list).to_dict()

json_arr=[]
for month,values in jsonfile.items():
    arr=[]
    for value in values:        
        for types, val in value.items():
            arr.append({"type": types, "values": val}) 
    json_arr.append({"month": month, "values": arr} )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM