我有以下json:
{
"repo_url":"git@github.plugin.git",
"latest_commit":"bfe7bxxxx",
"old_commit":"a4ccbyyy",
"region": {
"A":["us-south","us-east"],
"B":["au-syd","germany"]
}
}
如果我提供A
或us-east
作为输入,我需要获取键值us-south
。同样,如果我提供B
或au-syd
作为输入,我需要获得germany
。我如何遍历这个json构造。
我尝试过以下代码作为起点
output_json = json.load(open(file))
print output_json["region"]
for majorkey, subdict in output_json["region"]:
print subdict
但是这会抛出错误
for majorkey, subdict in output_json["region"]:
ValueError: too many values to unpack
答案 0 :(得分:2)
您需要使用iteritems
而不是仅仅迭代dict
In [3]: for k, v in output_json['region'].iteritems():
...: if 'us-south' in v:
...: print(v.index('us-south'))
...: print(k)
...:
0
A
答案 1 :(得分:1)
如评论中所述。这就是你可能想要的。
对于python3。*
for majorkey, subdict in output_json['region'].items():
print(subdict)
对于python2。*
for majorkey, subdict in output_json['region'].iteritems():
print(subdict)
答案 2 :(得分:1)
我在JavaScript中试过这个,希望它可以按照您的期望工作。
var jsonObj = {
"repo_url":"git@github.plugin.git",
"latest_commit":"bfe7bxxxx",
"old_commit":"a4ccbyyy",
"region": {
"A":["us-south","us-east"],
"B":["au-syd","germany"]
}
};
function input(val) {
for (var i in Object.keys(jsonObj.region)) {
for (var j in jsonObj.region[Object.keys(jsonObj.region)[i]]) {
if (jsonObj.region[Object.keys(jsonObj.region)[i]][j] == val) {
console.log(Object.keys(jsonObj.region)[i]);
}
}
}
}
input("us-east");