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

2024-04-27 00:55:04 发布

您现在位置: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