2017-11-11 100 views
0

這是我的JSON:ValueError異常在/後/不JSON對象可以被解碼

{ 
    "documents": [ 
       { 
       "score": 0.5, 
       "id": "1" 
        } 
       ], 
    "errors": [] 
} 

我想知道我怎麼能取「得分」而不將其轉換成字典因爲當我嘗試使用? json.loads它給我以下錯誤:

ValueError at /post/ 
No JSON object could be decoded 

這是我正在使用的代碼。

def GetSentiment(documents): 
    "Gets the sentiments for a set of documents and returns the 
    information." 
    headers = {'Ocp-Apim-Subscription-Key': accessKey} 
    conn = httplib.HTTPSConnection(uri) 
    body = json.dumps(documents) 
    conn.request("POST", path, body, headers) 
    response = conn.getresponse() 
    return response.read() 

documents = {'documents': [ 
         {'id': '1', 'language': 'en', 'text': caption}, 
      ]} 
result = GetSentiment(documents) 
resp_dict = json.loads(result) 
print resp_dict 
score = resp_dict["documents"][0]["score"] 
return score 
+0

(改進了代碼格式,使其更容易閱讀) – Anupam

+0

嗨,告訴我們你想做什麼,因爲也許你可以使用另一種方法 –

+0

@mohammedqudah我只想獲取分數值,因爲我想使用它進行情緒分析。要獲取分數值,我只能使用json.loads和那個bug。 –

回答

0

我看着你的JSON轉換的代碼,它是罰款:

>>> result = '{"documents": [{"score": 0.5,"id": "1"}],"errors": []}' 
>>> import json 
>>> resp_dict = json.loads(result) 
>>> score = resp_dict["documents"][0]["score"] 
>>> print score 
0.5 # success ! 

所以您的問題必須與result對象,這是不是你的建議。一定是你的GetSentiment函數有問題。

您的print result系列產生了什麼?另外,你有沒有嘗試過使用類似requests這樣的東西來讓你的生活更輕鬆?

相關問題