目标: 迭代子json查找2个键以获取特定字符串
在PHP中它很容易,但对于python 3,我似乎找不到合适的方法。我尝试了我在网上找到的其他解决方案,但我总是收到错误。
示例JSON:
{
"main1": {
"sub1": {
"prop1": "name1",
"prop2": "name2"
},
"sub2": {
"prop1": "name1",
"prop2": "name2"
},
},
"main2": {
"sub1": {
"prop1": "name1",
"prop2": "name2"
},
"sub2": {
"prop1": "name1",
"prop2": "name2"
},
},
}
代码
self.data = dataIO.load_json('data/data.json')
for item in self.data['main1'].items():
if item['prop1'] == 'name1' or item['prop2'] == 'name1':
print 'found one'
错误:
TypeError: string indices must be integers
答案 0 :(得分:0)
items()返回键值的元组,因此您必须使用item [1] [' prop1']:
for item in x['main1'].items():
if item[1]['prop1'] == 'name1' or item[1]['prop2'] == 'name1':
print 'found one'
或者更好,这样做:
self.data = dataIO.load_json('data/data.json')
for key,item in self.data['main1'].items():
if item['prop1'] == 'name1' or item['prop2'] == 'name1':
print 'found one'