2017-09-04 46 views
0

我有存儲在一個名爲dict其中rasa_decoded_output返回以下JSON json在類型錯誤解析JSON字典結果:列表索引必須是整數,而不是str的

{ 
    "entities": [ 

    ], 
    "intent_ranking": [ 
    { 
     "confidence": 0.712699869084774, 
     "name": "st_testing" 
    }, 
    { 
     "confidence": 0.033084814164303, 
     "name": "emergency" 
    }, 
    { 
     "confidence": 0.024547592443969, 
     "name": "exists_item" 
    }, 
    { 
     "confidence": 0.023160524284639, 
     "name": "check_out" 
    }, 
    { 
     "confidence": 0.022475491594176, 
     "name": "broken_climate" 
    }, 
    { 
     "confidence": 0.021986762111397, 
     "name": "exisits_hours_fitness_center" 
    }, 
    { 
     "confidence": 0.019758362302795, 
     "name": "st_compliment" 
    }, 
    { 
     "confidence": 0.019739803875883, 
     "name": "request_profane" 
    }, 
    { 
     "confidence": 0.01857200162444, 
     "name": "broken_catchall" 
    }, 
    { 
     "confidence": 0.016882101663941, 
     "name": "exists_vending" 
    } 
    ], 
    "intent": { 
    "confidence": 0.072699869084774, 
    "name": "st_testing" 
    }, 
    "text": "Testing this stuff" 
} 

我試圖提取第一次出現的confidencename,這我通過下面的代碼做:

intent_rank1 = rasa_decoded_output['intent_ranking']['name'] 
confidence_rank1 = rasa_decoded_output['intent_ranking']['confidence'] 

然而,這導致錯誤TypeError: list indices must be integers, not str。將json中的值存儲到對象中的正確方法是什麼?我不確定我的失誤在哪裏。我懷疑這與我的代碼中沒有指定哪個名稱或信任有關。

我的理解是,在這種情況下,它是一個dict沒有問題。使用json.dumps()並用相同的代碼查看結果TypeError: string indices must be integers

+0

'intent_rank1 = rasa_decoded_output [ 'intent_ranking'] [0] [ '名稱']' –

+1

而且,'confidence_rank1 = rasa_decoded_output [ 'intent_ranking'] [0] [ '信心']''的intent_ranking'是一個列表。 –

+0

添加了一個附加一些信息,爲後代的答案。如果你喜歡,請接受。謝謝。 –

回答

2

intent_ranking不是一本字典,而是一個字典清單。你需要沿着

intent_rank_i = rasa_decoded_output['intent_ranking'][i]['name'] 

或者線的東西,

confidence_rank_i = rasa_decoded_output['intent_ranking'][i]['confidence'] 

i是指在列表中的ith元素。

遍歷每一個值,你可以使用一個循環:

for d in rasa_decoded_output['intent_ranking']: 
    i = d['name'] 
    c = d['confidence'] 
    ... # something else 
0

下面將不起作用,因爲rasa_decoded_output['intent_ranking']list(陣列相當於像Java/C++/Java腳本其他語言)的dict小號。

intent_rank1 = rasa_decoded_output['intent_ranking']['name'] 

解決方案

  1. 如果您確信confidenceranking是要來的第一個項目在列表中,然後用這個 -

    intent_rank1 = rasa_decoded_output['intent_ranking'][0]['name'] 
    confidence_rank1 = rasa_decoded_output['intent_ranking'][0]['confidence'] 
    
  2. 否則,你可以使用以下內容

    data = { 
        "entities": [...], 
        "intent_ranking": [...] 
    }  
    
    def get_first_intent_and_confidence(data): 
        for info in data.get('intent_ranking', []): 
         if 'name' in info and 'confidence' in info: 
          return info['name'], info['confidence'] 
    
    intent, confidence = get_first_intent_and_confidence(data) 
    
+0

是的,注意到了。發佈一個修復。 – Killswitch

相關問題