【发布时间】:2019-05-03 10:51:50
【问题描述】:
I have JSON file as mentioned below,
**test.json**
{
"header1" :
{
"header1_body1":
{
"some_key":"some_value",
.......................
},
"header1_body2":
{
"some_key":"some_value",
.......................
}
},
"header2":
{
"header2_body1":
{
"some_key":"some_value",
.......................
},
"header2_body2":
{
"some_key":"some_value",
.......................
}
}
}
希望将 JSON 内容分组到如下列表中:
header1 = ['header1_body1','header1_body2']
header2 = ['header2_body1','header2_body2']
header1, header2 can be till ....header n。因此,必须创建包含其值的动态列表,如上所示。
我怎样才能做到这一点? 最佳的接近方法是什么?
解决方案:
with open('test.json') as json_data:
d = json.load(json_data)
for k,v in d.iteritems():
if k == "header1" or k == "header2":
globals()['{}'.format(k)] = d[k].keys()
现在,header1 和 header2 可以作为列表访问。
for i in header1:
print i
【问题讨论】:
-
首先,确保你的 json 格式正确,因为我看到你写了错误的 json 格式,它应该是
"header1_body2":{ ... } -
@ImamDigmi 抱歉,这是错字。感谢提及。
标签: python json list dictionary group-by