python - 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
解决方案
可能是这个 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']}
推荐阅读
- macos - launchctl load -w 没有那个文件或目录
- assembly - 如何在汇编代码中调用 fprintf() 函数?
- python-3.x - 为什么boto3的connect方法中的主机名不接受变量值
- php - 如何将 curl 设置为模块控制器
- batch-file - 制作批处理文件以传输文件名包含特定数字的文件
- javascript - 使用 WebRTC 进行直播
- xml - XSLT 修改属性值并添加新元素
- c# - Asp.Net Mvc Core 项目第一次尝试不编译
- amazon-web-services - 通过 AWS 开发工具包启用对 API Gateway 方法请求参数的缓存
- python - 使用while函数遇到python问题