Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中使用JSON响应中的数据_Python_Json - Fatal编程技术网

在python中使用JSON响应中的数据

在python中使用JSON响应中的数据,python,json,Python,Json,我目前正在使用Kairos进行一个小型人脸识别项目,我不知道如何使用我的响应数据。这是基于我发送的图片的数据: request = Request(url, data=values, headers=headers) response_body = urlopen(request).read() print(response_body) 我的回答是这样的,我想使用信心值: { "images": [ { "transaction": { "status":

我目前正在使用Kairos进行一个小型人脸识别项目,我不知道如何使用我的响应数据。这是基于我发送的图片的数据:

request = Request(url, data=values, headers=headers)
response_body = urlopen(request).read()
print(response_body)
我的回答是这样的,我想使用信心值:

{
"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"
}

如何从该代码中提取置信值?

您的响应是一个字符串。您需要的是python数据收集、字典/列表。要轻松解决此问题,只需使用json库中的loads方法即可

import loads from json
data = loads(response_body)
然后,为了获得置信值,您可以执行以下操作

confidence = data.images[0].transaction.confidence

你可以这样。你的回答是下一本词典

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

谢谢你的回复

我使用以下方法获得了正确的值:

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)

他说了什么。JSON格式的数据或多或少是一个奇特的格式字典。问题是如何获得信心值我编辑了我的回答,有一个关于json的Python文档页面。你读过吗?请求类是从哪里来的?如果请求模块,您可以使用json方法自动解码响应并返回Python dict。OP还没有dict,只有read返回的字节字符串。根据OP描述响应为dictionaryNo,printresponse_body的输出看起来像一个字典。比较print{'foo':1}与print{'foo':1}的输出。名为read的方法不太可能返回原始字节以外的任何内容。