如何在列表内循环遍历json字典

时间:2020-02-20 15:36:35

标签: python json loops

我正在进行网络抓取,并且我在一个看起来像这样的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

我尝试枚举列表,但仍然遇到相同的错误,并且还尝试使用键,值对但存在相同的错误。你能给我一个想法,我想错了吗?

+++因此,我根据注释中的建议运行了%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

2 个答案:

答案 0 :(得分:1)

如果您在the_dict中有多个json数据大块,请遍历每个大块:

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'])

答案 1 :(得分:0)

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