我的Json数据如下:
{
"context":[
{
"local":
[
{
"interface": "BDI200",
"desc":"eNODEB",
},
{
"interface": "BDI100",
"desc":"eNODEB",
}
]
},
{
"CPM": [
{
"interface": "BDI200",
"desc":"eNODEB",
},
{
"interface": "BDI100",
"desc":"eNODEB",
}
]
}
]
}
实际上,在“上下文”中,我有两个上下文“本地”和“ CPM”。要访问上下文元素,我必须静态地指定上下文名称(例如下面的代码)。在现实生活中,我有超过50种上下文,然后我如何不给出名称就可以访问。
import json
a=open('4.txt','r')
data=json.load(a)
print (data['context'][0]['local'])
答案 0 :(得分:0)
上下文是您所需要的数组,因此您可以简单地对其进行迭代:
for cntxt in data["context"]:
print(cntxt)
如果您可以控制json结构,则可以通过以下方式进行更改:
{
"context":
{
"local": [
{
"interface": "BDI200",
"desc":"eNODEB",
},
{
"interface": "BDI100",
"desc":"eNODEB",
}
],
"CPM": [
{
"interface": "BDI200",
"desc":"eNODEB",
},
{
"interface": "BDI100",
"desc":"eNODEB",
}
]
}
}
并更明确地对其进行迭代:
for name, context_data in a["context"].items():
print("Context's name:", name)
print("Data:", context_data)
答案 1 :(得分:0)
首先,您的json无效
我从下面的问题中做出了一个有效的json,
{
"context":[
{
"local":
[
{
"interface": "BDI200",
"desc":"eNODEB"
},
{
"interface": "BDI100",
"desc":"eNODEB"
}
]
},
{
"CPM": [
{
"interface": "BDI200",
"desc":"eNODEB"
},
{
"interface": "BDI100",
"desc":"eNODEB"
}
]
}
]
}
如果要遍历此json并获取所有本地,CPM等,请尝试
import json
a=open('4.txt','r')
data=json.load(a)
for k in data:
for j in data[k]:
d = j
for l in d:
print(l)
print(d[l])