我正在试用 json,因为我必须使用 Cisco API,但我不知道如何循环遍历 json 对象。我可以获取 key ,但无法获取值。
我正在使用 http://www.jsoneditoronline.org/对我来说理解 json 格式,但这是我到目前为止所拥有的..
json 文件:
{
"queryResponse" : {
"@rootUrl" : "\/webacs\/data",
"@requestUrl" : "https : \/\/192.168.116.207\/webacs\/api\/v1\/data\/DeviceGroups\/42",
"@responseType" : "getEntity",
"entity" : {
"@url" : "\/webacs\/data\/className\/15",
"@type" : "className",
"@dtoType" : "deviceGroupsDTO_$$_javassist_5196",
"deviceGroupsDTO" : {
"@id" : "15",
"@displayName" : "String value",
"clearedAlarms" : 1,
"criticalAlarms" : 1,
"groupId" : 2,
"groupName" : "String value",
"informationAlarms" : 1,
"majorAlarms" : 1,
"minorAlarms" : 1,
"name" : "String value",
"warningAlarms" : 1
}
}
}
}
我的 python 脚本:
import json
jsondata = json.load(open('data.json'))
for rows in jsondata['queryResponse']['entity']['deviceGroupsDTO']:
print(rows)
它打印的是:
name
@id
warningAlarms
@displayName
informationAlarms
clearedAlarms
majorAlarms
groupId
groupName
criticalAlarms
minorAlarms
不知道我做错了什么......
请您参考如下方法:
jsondata['queryResponse']['entity']['deviceGroupsDTO'] 是一个字典。
遍历 items()获取键值对:
for key, value in jsondata['queryResponse']['entity']['deviceGroupsDTO'].items():
print(key, value)
请注意,如果是 python2,您最好使用 iteritems()代替 items() .
另请参阅:What is the difference between dict.items() and dict.iteritems()?
