2017-11-11 93 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这样的东西来让你的生活更轻松?

相关问题