Python requests - extracting data from response.text

后端 未结 1 1956
情歌与酒
情歌与酒 2020-12-10 06:45

I have been looking around for a few days now and cannot figure this out. Basically I\'m uploading an image to a server and get an ID in return, the problem is I cannot figu

相关标签:
1条回答
  • 2020-12-10 07:17

    You are receiving JSON; you already use the response.json() method to decode that to a Python structure:

    data = r.json()
    

    You can treat data['uploaded'] as any other Python list; the content is just the one dictionary, so another dictionary key to get the id value:

    data['uploaded'][0]['id']
    

    It is safe to hardcode the index to [0] here as you know how many images you uploaded.

    You could use exception handling to detect if anything unexpected was returned:

    try:
        image_id = data['uploaded'][0]['id']
    except (IndexError, KeyError):
        # key or index is missing, handle an unexpected response
        log.error('Unexpected response after uploading image, got %r',
                  data)
    

    or you could handle data['status']; it all depends on the exact semantics of the API you are using here.

    0 讨论(0)
提交回复
热议问题