解析请求后响应中的JSON嵌套数据

2024-05-19 02:13:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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


Tags: and项目jsondatacontentutf8postrequests
1条回答
网友
1楼 · 发布于 2024-05-19 02:13:22

您正在使用resp.content以原始字节的形式检索数据

试试resp.json()。这将把JSON解码成Python对象

相关问题 更多 >

    热门问题