簡體   English   中英

如何遍歷列表中的json字典

[英]How to loop through json dictionary inside of list

我正在做網絡抓取,我在一個 json 對象中得到了數據,如下所示:

{'categories': '[{"title":"Name", "desc":"Mike"}, {"title":"Food", "desc":"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

如果在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'])

或者,如果您知道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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM