簡體   English   中英

通過嵌套的JSON對象進行迭代

[英]Iteration through nested JSON objects

我是Python的初學者,可以提取由嵌套對象(字典?)組成的JSON數據。 我正在嘗試遍歷所有內容以找到它們共享的鍵,並僅選擇在該鍵中具有特定值的對象。 我花了幾天的時間研究和應用,現在在JS / Python分析癱瘓的混合中一切都變得模糊起來。 這是JSON數據的通用格式:

{
    "things":{
        "firstThing":{
            "one":"x",
            "two":"y",
            "three":"z"
        },
        "secondThing":{
            "one":"a",
            "two":"b",
            "three":"c"
        },
        "thirdThing":{
            "one":"x",
            "two":"y",
            "three":"z"
        }
    }
}

在此示例中,我想隔離兩個== y的字典。 我不確定是否應該使用

  1. JSON選擇(things.things [i] .two)
  2. 循環遍歷事物,然后事物[i]尋找兩個
  3. 當我有3組鍵時,k / v

誰能指出我正確的方向?

假設這僅僅是一個深度( things ),並且您希望此字典的“副本”僅包含匹配的子字典,那么您可以通過字典理解來做到這一點:

data = {
    "things":{
        "firstThing":{
            "one":"x",
            "two":"y",
            "three":"z"
        },
        "secondThing":{
            "one":"a",
            "two":"b",
            "three":"c"
        },
        "thirdThing":{
            "one":"x",
            "two":"y",
            "three":"z"
        }
    }
}

print({"things": {k:v for k, v in data['things'].items() if 'two' in v and v['two'] == 'y'}})

由於您已使用python標記了此標簽,因此我假設您希望使用python解決方案。 如果您知道“兩個”鍵(無論它是什么)僅出現在所需對象的級別,那么這可能是遞歸解決方案的好地方:生成器使用字典並產生任何子字典,具有正確的鍵和值。 這樣,您不必考慮過多的數據結構。 如果您至少使用Python 3.3,則類似的方法將起作用:

def findSubdictsMatching(target, targetKey, targetValue):
    if not isinstance(target, dict):
        # base case
        return
    # check "in" rather than get() to allow None as target value
    if targetKey in target and targetKey[target] == targetValue:
        yield target
    else:
        for key, value in target.items():
            yield from findSubdictsMatching(value, targetKey, targetValue)

此代碼允許您添加帶有“ two”:“ y”的對象以列出:

import json
m = '{"things":{"firstThing":{"one":"x","two":"y","three":"z"},"secondThing":{"one":"a","two":"b","three":"c"},"thirdThing":{"one":"x","two":"y","three":"z"}}}'
l = json.loads(m)
y_objects = []
for key in l["things"]:
    l_2 = l["things"][key]
    for key_1 in l_2:
        if key_1 == "two":
            if l_2[key_1] == 'y':
                y_objects.append(l_2)

print(y_objects)

安慰:

[{'one': 'x', 'two': 'y', 'three': 'z'}, {'one': 'x', 'two': 'y', 'three': 'z'}]

暫無
暫無

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

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