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?

2
  • 1
    There's a Python documentation page on json. Have you read it? Commented Nov 2, 2017 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. Commented Nov 2, 2017 at 13:58

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

3 Comments

what he said. JSON formatted data is more or less a fancy formatted dictionary. Make sure you are reading it as one.
The question asked how to get the confidence value
I edited my answer
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)

Comments

-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
>>> 

3 Comments

The OP doesn't have a dict yet, just the byte string returned by read.
As per OP desciption response is dictionary
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.