简体   繁体   中英

How to create a nested array of JSON objects using Python?

Desired output:

{"MainKey": 
   [{"key01":"value01","key02":"value02"},
    {"key11":"value11","key22":"value02"}
   ]
}

The code I tried:

data = {}
data2=[{}]

data2[0]['key01'] = 'value01'
data2[0]['key02']=  'value02'

data2[1]['key11'] = 'value11'  #index out of bounds error
data2[1]['key12']=  'value12'

data['MainKey']=data2

import json 
with open('try.json", 'w') as outfile:
 json.dump(data,outfile)

But this gives index out of bounds error for the second set of values in data2. How do i solve this?

One approach is to create the number of dict using range .

Ex:

data = {}

data2 = [{} for i in range(2)]

data2[0]['key01'] = 'value01'
data2[0]['key02']=  'value02'

data2[1]['key11'] = 'value11'
data2[1]['key12']=  'value12'

data['MainKey']=data2
print(data)

Output:

{'MainKey': [{'key01': 'value01', 'key02': 'value02'}, {'key12': 'value12', 'key11': 'value11'}]}

data2 is a list with only one item, so its index cannot be greater than 0.

>>> data2=[{}]
>>> data2[0]['key01'] = 'value01'
>>> data2[0]['key02'] = 'value02'
>>> data2

[{'key01': 'value01', 'key02': 'value02'}]

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