简体   繁体   English

从 Requests POST 响应中解析 JSON 嵌套数据

[英]Parse JSON nested data from Requests POST response

I'm working on a project using Python(3.7) in which I have to parse a JSON returned from the POST request using Requests library.我正在使用 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!我搜索了很多并尝试了太多解决方案,但没有任何帮助,所以请不要将其标记为重复!

Here's what I have tried:这是我尝试过的:

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("'", '"')

When I print the resp it provide the following JSON:当我打印resp时,它提供以下 JSON:

{
    "code": "00",
    "message": "Successful",
    "data": "{\"requestId\":\"0012602\",\"responseCode\":\"68\",\"responseDescription\":\"Invalid Institution Code\"}"
}

Now, I need to access the data field of that JSON, here what I tried:现在,我需要访问该 JSON 的data字段,这里我尝试了:

resp['data']

But it returns an error as:但它返回一个错误:

string indices must be integers字符串索引必须是整数

You're retrieving the data as raw bytes by using resp.content .您正在使用resp.content将数据作为原始字节检索。

Try resp.json() instead.尝试resp.json()代替。 This will decode the JSON into Python objects.这会将 JSON 解码为 Python 对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM