繁体   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