通过嵌套json对python中的特定键进行递归迭代

时间:2014-01-09 19:06:27

标签: python json recursion iteration list-comprehension

我正在尝试从json文件中提取嵌套值。我想打印出每个“id”键的每个值。我认为我很接近,但无法弄清楚为什么obj类型从dict变为列表,然后为什么我无法解析该列表。 这是我正在使用的json的链接:http://hastebin.com/ratevimixa.tex

这是我目前的代码:

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import json

json_data = open('JubJubProductions.json', 'r+')
jdata = json.loads(json_data.read().decode("utf-8"))

def recursion(dict):

    for key, value in dict.items():

        if type(value) == type(dict):
            if key != "paging":
                for key, value in value.items():
                    if isinstance (value,list):
                        print key
                        # place where I need to enter list comprehension?
                if type(value) == type(dict):
                    if key == "id":
                        print " id found " + value
                    if key != "id":
                        print key + " 1st level"
                if key == "id":
                    print key
        else:
            if key == "id":
                print "id found " + value       
if __name__ == '__main__':
    recursion(jdata)

----------------------------------------------- --------------------------------------------的更新

现在我正在使用它,它将返回一个id值,但不是全部:

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import json

json_data = open('jubjubProductions', 'r+')
jdata = json.loads(json_data.read().decode("utf-8"))

def id_generator(d):
    for k, v in d.items():
        if k == "id":
            yield v
        elif isinstance(v, dict):
            for id_val in id_generator(v):
                yield id_val

if __name__ == '__main__':
    for _ in id_generator(jdata):
        print (_)

4 个答案:

答案 0 :(得分:18)

JSON可能包含需要搜索的对象列表:

Python 2.7版本:

def item_generator(json_input, lookup_key):
    if isinstance(json_input, dict):
        for k, v in json_input.iteritems():
            if k == lookup_key:
                yield v
            else:
                for child_val in item_generator(v, lookup_key):
                    yield child_val
    elif isinstance(json_input, list):
        for item in json_input:
            for item_val in item_generator(item, lookup_key):
                yield item_val

Python 3.x版本:

def item_generator(json_input, lookup_key):
    if isinstance(json_input, dict):
        for k, v in json_input.items():
            if k == lookup_key:
                yield v
            else:
                yield from item_generator(v, lookup_key)
    elif isinstance(json_input, list):
        for item in json_input:
            yield from item_generator(item, lookup_key)

答案 1 :(得分:11)

def id_generator(dict_var):
      for k, v in dict_var.items():
            if k == "id":
                 yield v
            elif isinstance(v, dict):
                 for id_val in id_generator(v):
                       yield id_val

这将创建一个迭代器,它将在键“id”下的任何级别上产生每个值。示例用法(打印所有这些值):

for _ in id_generator(some_json_dict):
     print(_)

答案 2 :(得分:0)

一点更简洁的代码(在python 3.x中)。

def parse_json_recursively(json_object, target_key):
    if type(json_object) is dict and json_object:
        for key in json_object:
            if key == target_key:
                print("{}: {}".format(target_key, json_object[key]))
            parse_json_recursively(json_object[key], target_key)

    elif type(json_object) is list and json_object:
        for item in json_object:
            parse_json_recursively(item, target_key)


json_object = {"key1": "val1", "key2": [{"key3":"val3", "key4": "val4"}, 123, "abc"]}
target_key = "key3"
parse_json_recursively(json_object, target_key) # Ouput key3: val3

答案 3 :(得分:0)

def get_val(j, s, v=None):
for k in j:
    if v == None and k == s:
        return j[k]
    elif v != None and k == s and v == j[k]:
        return True
    elif v != None and k == s and v != j[k]:
        return False
    elif isinstance(j[k], dict):
        return get_val(j[k], s, v)

您可以将with与下面的json列表一起使用

for l in j:
    r = get_val(l, 'key')
    print(r)

for l in j:
    r = get_val(l, 'mac', '00-60-2F-5A-04-51')
    print(r)