小编典典

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

json

我正在尝试从json文件中提取嵌套值。我想打印出每个“
id”键的每个值。我想我已经接近了,但无法弄清楚为什么obj类型从字典更改为列表,然后为什么我无法解析该列表。这是我正在使用的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 (_)

阅读 246

收藏
2020-07-27

共1个答案

小编典典

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(_)
2020-07-27