通过嵌套的JSON对象进行迭代

时间:2018-02-04 17:38:39

标签: python json

我是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套钥匙时
  4. k / v
  5. 有人能指出我正确的方向吗?

3 个答案:

答案 0 :(得分:0)

假设这只是一个深度(things),并且你希望这个字典的'重复'只包含匹配的子dicts,那么你可以用字典理解来做到这一点:

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'}})

答案 1 :(得分:0)

由于你用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)

答案 2 :(得分:0)

此代码允许您使用" 2":" 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'}]