如何在python中获取某个名称键的项值?
我读到的对象是:如何在python中获取某个名称键的项值?,python,json,parsing,Python,Json,Parsing,我读到的对象是: data = json.load(urllib2.urlopen(url)) 我有这样的JSON: {"state": [{"connected": true, "name": "smtp"}] {"connected": true, "name": "emailer"} {"connected": true, "name": "mysql"} {"con
data = json.load(urllib2.urlopen(url))
我有这样的JSON:
{"state":
[{"connected": true, "name": "smtp"}]
{"connected": true, "name": "emailer"}
{"connected": true, "name": "mysql"}
{"connected": true, "name": "mongodb"}
{"connected": true, "name": "redis"}
{"state":
[{"connected": true, "name": "mysql"}
{"connected": true, "name": "mongodb"}]
"connected": true, "name": "vault"}
我应该使用什么来获取具有任何名称的项目的连接状态?例如,“mysql”-“true”。
JSON的结构将来可以更改,这就是为什么我不想使用这样的代码:
print data['state'][0]['connected']
使用递归函数以如下方式构建辅助表如何:
def buildConnectionTable(table):
result = {}
if type[table] == list:
subresult = buildConnectionTable(table[0])
result.update(subresult)
for key, value in table.items():
if key == state:
subresult = buildConnectionTable(value)
result.update(subresult)
else:
result[value["name"]] = value["connected"]
return result
connection_table = buildConnectionTable(data)
print connection_table["mysql"]
print connection_table["vault"]
print connection_table["redis"]
这可能不是正确的代码,因为我目前无法对其进行测试,但希望它至少演示了问题的可能解决方案