Extract '_id' from load_response object

Asked

Viewed 47 times

0

After post, I get an object load_response, in Dict format, with the following structure:

{'_content': b'{"params":{},"_id":"5a566f175ff52e02704de1aa","variables":"/dataset/5a566f175ff52e02704de1aa/variables","scenarios":"/dataset/5a566f175ff52e02704de1aa/scenarios","client_code":"test","tags":["test"]}',
 '_content_consumed': True,
 'connection': <requests.adapters.HTTPAdapter at 0x111103d30>,
 'cookies': <RequestsCookieJar[]>,
 'elapsed': datetime.timedelta(0, 25, 923809),
 'encoding': 'UTF-8',
 'headers': {'Server': 'waitress', 'Content-Length': '215', 'Content-Type': 'text/html; charset=UTF-8', 'Date': 'Wed, 10 Jan 2018 19:52:29 GMT'},
 'history': [],
 'raw': <requests.packages.urllib3.response.HTTPResponse at 0x113bd1240>,
 'reason': 'Created',
 'request': <PreparedRequest [POST]>,
 'status_code': 201,
 'url': 'http://localhost:8080/xfg/v2.0/dataset'}

I wonder how I can extract the value of the "_id" field from this dictionary.

1 answer

1


You have, serialized as a byte string, another JSON object, which is the key content _content. It is easy to see this because you have the structure of a dictionary, and other typical JSON format formats fully contained between markers b' and '. So, supposing that what you put into the question is within the variable data, you can do:

import json
...
# data = request.json()  # Uma das formas de chegar até onde você está
...
inner_data = json.loads(data["_content"])
id = inner_data["_id"] 

By default, Python json.loads assumes that the byte string is in utf-8. Some web forms and old codes can send the encoding as "latin1" - in this case, you must decode the string before passing it to loads:

inner_data = json.loads(data["_content"].decode("latin1"))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.