Extract '_id' from object load_response

0

After posting, I get a load_response object, 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 would like to know how to extract the value of the "_id" field from this dictionary.

    
asked by anonymous 11.01.2018 / 11:19

1 answer

1

You have, serialized as a string of bytes, another JSON object, which is the contents of the _content key. It's easy to see why you have the structure of a dictionary, and other typical JSON formatting completely retained between the b' and ' markers. So assuming what you put into the question is within the data variable, 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, the json.loads of Python assumes that the byte string is in utf-8. Some web forms and old codes may have the encoding as "latin1" - in which case, you must decode the string before passing it to loads :

inner_data = json.loads(data["_content"].decode("latin1"))
    
13.01.2018 / 02:57