如何循环浏览列表中的json字典

2024-05-23 13:38:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做网页抓取,我在一个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

Tags: theinjsonfortitlefood错误range
2条回答
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  

如果在the_dict中有多个json数据blob,请迭代每个blob:

for jsondata in the_dict.values(): 
    for d in json.loads(jsondata):
        if d.get('title') == 'Food':
            print(d['desc'])

或者,如果您知道the_dict中只有一个json数据块,并且它位于'categories'键下:

for d in json.loads(the_dict['categories']):
    if d.get('title') == 'Food':
        print(d['desc'])

相关问题 更多 >