[英]How to loop through json dictionary inside of list
I am doing web scraping, and I got data in a json object that looks like this:我正在做网络抓取,我在一个 json 对象中得到了数据,如下所示:
{'categories': '[{"title":"Name", "desc":"Mike"}, {"title":"Food", "desc":"Muffin"}]'}
And I want to loop through this dictionary and just get one value "Muffin".我想遍历这本字典,只得到一个值“松饼”。 My code is:
我的代码是:
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
I get expected output, however I keep getting the error:我得到了预期的输出,但是我不断收到错误消息:
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
I tried enumerating the list but still get the same error, and also tried using a key, value pair but the same error.我尝试枚举列表但仍然得到相同的错误,并且还尝试使用键值对但出现相同的错误。 Can you give me an idea where I'm thinking wrong?
你能告诉我我哪里想错了吗?
+++ So I have run %xmode Verbose according to the suggestion in the comment, and I got the following error: +++ 所以我根据评论中的建议运行了 %xmode Verbose ,但出现以下错误:
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
If you have multiple blobs of json data in the_dict
iterate over each blob:如果在
the_dict
有多个 json 数据 blob, the_dict
遍历每个 blob:
for jsondata in the_dict.values():
for d in json.loads(jsondata):
if d.get('title') == 'Food':
print(d['desc'])
or if you know there is only one blob of json data in the_dict
and it's under the key 'categories'
:或者,如果您知道
the_dict
只有一个 json 数据 blob 并且它位于关键的'categories'
:
for d in json.loads(the_dict['categories']):
if d.get('title') == 'Food':
print(d['desc'])
for key, values in the_dict.items():
jvalues = json.loads(values)
for val in jvalues:
muff_filter = json.loads(val)['title']
if muff_filter == 'Food':
print(json.loads(val)['desc'])
else:
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.