我有以下json:
{
"repo_url":"git@github.plugin.git",
"latest_commit":"bfe7bxxxx",
"old_commit":"a4ccbyyy",
"region": {
"A":["us-south","us-east"],
"B":["au-syd","germany"]
}
}
如果我提供us-east
或us-south
作为输入,我需要获取A
键值。同样,如果我提供au-syd
或germany
作为输入,我需要获得B
。如何遍历此 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
你需要
使用iteritems
,而不仅仅是迭代字典
In [3]: for k, v in output_json['region'].iteritems():
...: if 'us-south' in v:
...: print(v.index('us-south'))
...: print(k)
...:
0
A
如评论中所述。这是你可能想要的。
对于 python3。
for majorkey, subdict in output_json['region'].items():
print(subdict)
对于 python2.*
for majorkey, subdict in output_json['region'].iteritems():
print(subdict)
我在 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");