简体   繁体   中英

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.

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:

{
    "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:

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 .

Try resp.json() instead. This will decode the JSON into Python objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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