【发布时间】:2014-01-28 12:30:01
【问题描述】:
我正在尝试从 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 (_)
【问题讨论】:
-
当我使用它时,我得到一个错误“太多的值无法解压”。我没有使用 d.items() 否则我会得到“AttributeError: 'unicode' object has no attribute 'items'”
标签: python json recursion iteration list-comprehension