Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

json - Python requests - extracting data from response.text

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 figure out how to extract this ID and change it into a String ready to be saved into a database.

Program Code

url = <Server address>
with open("image.jpg", "rb") as image_file:
    files = {'file': image_file}
    auth = ('<Key>', '<Pass>')
    r = requests.post(url, files=files, auth=auth)

data = r.json()
uploaded = data.get('uploaded')
content_id = uploaded[0]


print r
print r.text
print '--------------'
print str(content_id)

And here is the output I get

<Response [200]>
{
    "status": "success",
    "uploaded": [
        {
            "filename": "image.jpg",
            "id": "6476edfa1d262ad81181d992da78149d"
        }
     ]
}

--------------
{u'id': u'6476edfa1d262ad81181d992da78149d', u'filename': u'image.jpg'}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...