首页 > 解决方案 > ValueError:无法解码 JSON 对象 - Python 2.7 脚本

问题描述

我正在运行基于 HP Warranty API 的脚本(这是他们提供的示例代码),我收到“ValueError: No JSON object could be decoded”错误。我不确定如何进行。

我已经三次检查了我的 API 密钥/秘密。我目前正在使用 python 2.7.12。

我切断了代码的末尾以节省空间,但这就是我卡住的地方。

import requests
import json
import time
import dateutil.parser
import datetime

apiKey='mykey'
apiSecret='mysecret'
tokenBody = { 'apiKey': apiKey, 'apiSecret': apiSecret, 'grantType': 'client_credentials', 'scope': 'warranty' }

data = [
    #{ 'sn': '5CG7194P32', 'pn': 'V7B61UC' },
    { 'sn': '5CG7194P32', 'pn': 'V7B61UC' }
]
def _url(path):
    return 'https://css.api.hp.com' + path

# Get the access token
tokenHeaders = { 'Accept': 'application/json' }
tokenResponse = requests.post(_url('/oauth/v1/token'), data=tokenBody, headers=tokenHeaders)
tokenJson = tokenResponse.json() #GETTING STUCK HERE
token = tokenJson['access_token']

# Create the batch job
jobHeaders = {
    'Accept': 'application/json',
    'Authorization': 'Bearer ' + token,
    'Content-Type': 'application/json'
}
print('Creating new batch job...')
jobResponse = requests.post(_url('/productWarranty/v2/jobs/'), data=json.dumps(data), headers=jobHeaders)
job = jobResponse.json()
print('Batch job created successfully.')
print('--------------------')
print('Job ID: ' + job['jobId'])
print('Estimated time in seconds to completion: ' + str(job['estimatedTime']))
print('')

这是回溯:

Traceback (most recent call last):
  File "hp_test2.py", line 22, in <module>
    tokenJson = tokenResponse.json()
  File "/usr/lib/python2.7/dist-packages/requests/models.py", line 800, in json
    self.content.decode(encoding), **kwargs
  File "/usr/lib/python2.7/json/__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

在下面的评论中添加答案:

Content: scope=warranty&apiKey=mykey&apiSecret=mysecret&grantType=client_credentials
Status Code: 200

标签: pythonjsonpython-2.7

解决方案


可能是这个 API 发生了变化,它不再返回 JSON (?)。尝试进一步阅读文档以检查是否有另一种请求 JSON 数据的方法,这Accept: application/json似乎被服务器忽略了。

现在,假设您的响应始终是 JSON 或查询参数,您可以对其进行一些调整:

import urlparse

...

try:
    job = jobResponse.json()
except ValueError:
    job = urlparse.parse_qs(jobResponse.content)

无论哪种方式,您都会从响应中获得字典。考虑到parse_qs返回字典的值是否list()符合 RFC 规范:

{'scope': ['warranty'], 'apiKey': ['mykey'], 'apiSecret': ['mysecret'], 'grantType': ['client_credentials']}

推荐阅读