简体   繁体   English

python:遍历列表值并获取json中的键

[英]python : Iterate through the list values and get the key in json

I have the below json: 我有以下json:

{
    "repo_url":"git@github.plugin.git",
    "latest_commit":"bfe7bxxxx",
    "old_commit":"a4ccbyyy",
    "region": {
                    "A":["us-south","us-east"],
                    "B":["au-syd","germany"]
            }
 }

I need to get the key value A if I provide us-east or us-south as input. 如果我提供us-eastus-south作为输入,则需要获取键值A Similarly I need to get B if I provide au-syd or germany as input. 同样,如果我提供au-sydgermany作为输入,我需要获得B How do I loop through this json construct. 我如何遍历这个json构造。

I have tried below code as a starting point 我已经尝试过以下代码作为起点

 output_json = json.load(open(file))
            print output_json["region"]

            for majorkey, subdict in output_json["region"]:
                print subdict

But that throws below error 但这引发了错误

for majorkey, subdict in output_json["region"]:
ValueError: too many values to unpack

You need to use iteritems instead of just iterating over dict 您需要使用迭代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

As stated in the comments. 如评论中所述。 This is what you may want. 这就是您可能想要的。

For python3.* 对于python3。*

for majorkey, subdict in output_json['region'].items():
    print(subdict)

For python2.* 对于python2。*

for majorkey, subdict in output_json['region'].iteritems():
    print(subdict)

I tried this in JavaScript, I hope it will work as per your expectation. 我在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"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM