我似乎遇到了一个奇怪的阻止程序,试图访问JSON数据结构中的一些数据项。
我需要在JSON中迭代数据数组中的项目,但无法确定如何访问它们。
我试过这个:
import json
from pprint import pprint
file = 'data.json'
with open(file) as data_file:
data = json.load(data_file)
for host in data:
print host["host"]
for proto in host["protocols"]:
print proto
这让我得到了我的协议版本,但我无法找到如何获取数据数组中的项目。
[
{
"host": "192.168.0.1",
"port": 443,
"protocols": {
"v1": {
"data": ["12345","54354334534253245342"],
"tag": "abc"
},
"v2": {
"data": ["45678"],
"tag": "xyz"
}
},
"processed": false
},
{
"host": "192.168.0.3",
"port": 443,
"protocols": {
"v1": {
"data": ["12345","43434","543543543"],
"tag": "abc"
},
"v2": {
"data": ["45678"],
"tag": "xyz"
},
"v3": {
"data": ["910111"],
"tag": "ttt"
}
},
"processed": false
}
]
答案 0 :(得分:5)
Protocols是一个字典,所以你需要以不同的方式迭代它:
import json
from pprint import pprint
file = 'data.json'
with open(file) as data_file:
data = json.load(data_file)
for host in data:
print host["host"]
for version, proto in host["protocols"].iteritems():
print version
print proto
print proto["data"]