簡體   English   中英

python:遍歷列表值並獲取json中的鍵

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

我有以下json:

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

如果我提供us-eastus-south作為輸入,則需要獲取鍵值A 同樣,如果我提供au-sydgermany作為輸入,我需要獲得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"); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM