这是我当前的代码:
#!/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 (_)
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(_)