0

I am currently working on a small face recognition project using Kairos, and I can't figure out how to use my response data. This is based on the data of the picture i'm sending:

request = Request(url, data=values, headers=headers)
response_body = urlopen(request).read()
print(response_body)

My response is something like this, where I want to use the "confidence" value:

{
"images": [
    {
      "transaction": {
        "status": "success",
        "width": 327,
        "topLeftX": 512,
        "topLeftY": 466,
        "gallery_name": "MyGallery",
        "subject_id": "XXX",
        "confidence": 0.70211,
        "quality": -0.06333,
        "eyeDistance": 145,
        "height": 328
      }
    }
  ],
  "uploaded_image_url": "https://XXX"
}

How do I extract the value "confidence" from this code?

Sneh Pandya
  • 8,197
  • 7
  • 35
  • 50
Sokk
  • 1
  • 1
    There's a Python documentation page on json. Have you read it? – OneCricketeer Nov 02 '17 at 13:52
  • Where did the `Request` class come from? If the `requests` module, you can use the `json` method to decode the response automatically and get back a Python `dict`. – chepner Nov 02 '17 at 13:58

3 Answers3

2

Your response is a string. What you want is a python data collection, dictionary/ list. To easily solve this problem, you can simply use the loads method from the json library.

import loads from json
data = loads(response_body)

Then to get the confidence value you can do

confidence = data.images[0].transaction.confidence
Axnyff
  • 9,213
  • 4
  • 33
  • 37
0

Thanks for the responses.

I got the correct value by using:

request = Request(url, data=values, headers=headers)
response_body = json.loads(urlopen(request).read())
confidence = response_body.get('images')[0].get('transaction').get('confidence')
print(confidence)
Sokk
  • 1
-1

You can get like this. Your response is a nexted dictionary

>>> resp
{'images': [{'transaction': {'status': 'success', 'width': 327, 'topLeftX': 512, 'topLeftY': 466, 'gallery_name': 'MyGallery', 'subject_id': 'XXX', 'height': 328, 'quality': -0.06333, 'confidence': 0.70211, 'eyeDistance': 145}}], 'uploaded_image_url': 'https://XXX'}

>>> resp.get('images')[0].get('transaction').get('confidence')
0.70211
>>> 
Sandeep Lade
  • 1,865
  • 2
  • 13
  • 23
  • The OP doesn't have a `dict` yet, just the byte string returned by `read`. – chepner Nov 02 '17 at 13:59
  • As per OP desciption response is dictionary – Sandeep Lade Nov 02 '17 at 14:00
  • No, the output of `print(response_body)` *looks* like a dictionary. Compare the output of `print({'foo': 1})` with `print("{'foo': 1}")`. It's unlikely that a method named `read` is returning anything other than raw bytes. – chepner Nov 02 '17 at 14:09