如何使用Python创建嵌套的JSON对象数组?

时间:2018-06-18 10:05:26

标签: python arrays json python-3.x

期望的输出:

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

我试过的代码:

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)

但是这为data2中的第二组值提供了索引超出范围的错误。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

一种方法是使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>Move your mouse to calculate distance between the center of the element and the mouse cursor.</p> <p id="distance">Distance: <span>0</span>px</p> <div id="element"></div>创建字典数。

<强>实施例

range

<强>输出:

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)

答案 1 :(得分:0)

data2是一个只有一个项目的列表,因此其索引不能大于0。

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

[{&#39; key01&#39;:&#39; value01&#39;,&#39; key02&#39;:&#39; value02&#39;}]