我在做网页抓取,我在一个json对象中获得了如下数据:
{'categories': '[{"title":"Name", "desc":"Mike"}, {"title":"Food", "desc":"Muffin"}]'}
我想循环浏览这本字典,只得到一个值“Muffin”。 我的代码是:
for item in the_dict:
for i in range(0, len(item)-1):
muff_filter = json.loads(the_dict['categories'])[i]['title']
if muff_filter == 'Food':
print(json.loads(the_dict['categories'])[i]['desc'])
else:
pass
我得到了预期的输出,但是我不断得到错误:
Muffin
---------------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-50-9a650257d42a> in <module>
61 for item in the_dict:
62 for i in range(0, len(item)-1):
---> 63 food_filter = json.loads(the_dict['categories'])[i]['title']
64 if food_filter == 'Food':
65 print(json.loads(the_dict['categories'])[i]['desc'])
IndexError: list index out of range
我尝试枚举列表,但仍然得到相同的错误,还尝试使用键、值对,但出现相同的错误。你能告诉我我哪里想错了吗
+++因此我根据评论中的建议运行了%xmodeverbose, 我得到了以下错误:
Muffin
--------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-68-e1844b3cae82> in <module>
61 for item in get_cert:
62 for i in range(0, len(item)-2):
---> 63 the_dict= json.loads(the_dict['categories'])[i]['title']
global get_cert = {'categories': '[{"title":"Name","desc":"Mike"},{"title":"Food","desc":"Muffin"}]'}
global i = 2
64 if muff_filter == 'Food':
65 print(json.loads(the_dict['categories'])[i]['desc'])
IndexError: list index out of range
如果在
the_dict
中有多个json数据blob,请迭代每个blob:或者,如果您知道
the_dict
中只有一个json数据块,并且它位于'categories'
键下:相关问题 更多 >
编程相关推荐