我正在使用Python(3.7)进行一个项目,其中我必须使用Requests
库解析POST请求返回的JSON
I googled a lot and tried too many solutions but nothing helped me, so don't mark this as duplicate, please!
以下是我尝试过的:
def process_req(payload):
try:
headers = {
'Content-Type': 'application/json'
}
data = payload
resp = requests.post(
'http://<EXAMPLE_URL>',
data=data,
headers=headers
)
print('returned data: {}'.format(resp.content.decode('utf8').replace("'", '"')))
resp = resp.content.decode('utf8').replace("'", '"')
当我打印resp
时,它提供以下JSON:
{
"code": "00",
"message": "Successful",
"data": "{\"requestId\":\"0012602\",\"responseCode\":\"68\",\"responseDescription\":\"Invalid Institution Code\"}"
}
现在,我需要访问该JSON的data
字段,这里是我尝试的:
resp['data']
但它返回一个错误,如下所示:
string indices must be integers
您正在使用
resp.content
以原始字节的形式检索数据试试
resp.json()
。这将把JSON解码成Python对象相关问题 更多 >
编程相关推荐