如何在Python中获取JSON的字段特定值?

2024-01-08

我目前正在研究从 json 中提取字段,然后对其进行一些利用。因此我有面部参数,并且我想存储每个字段的值。我正在尝试从面部 JSON 中获取性别值: JSON如下:

{
  "face": [
    {
      "attribute": {
        "age": {
          "range": 5,
          "value": 24
        },
        "gender": {
          "confidence": 99.9999,
          "value": "Female"
        },
        "glass": {
          "confidence": 99.4157,
          "value": "None"
        },
        "pose": {
          "pitch_angle": {
            "value": 0.000001
          },
          "roll_angle": {
            "value": 0.650337
          },
          "yaw_angle": {
            "value": -0.42409
          }
        },
        "race": {
          "confidence": 98.058,
          "value": "Asian"
        },
        "smiling": {
          "value": 3.78394
        }
      },
      "face_id": "42245f24335ad21ea7c54f2db96a09b3",
      "position": {
        "center": {
          "x": 50.121951,
          "y": 35.97561
        },
        "eye_left": {
          "x": 43.465122,
          "y": 30.670488
        },
        "eye_right": {
          "x": 56.80878,
          "y": 30.821951
        },
        "height": 27.560976,
        "mouth_left": {
          "x": 45.649512,
          "y": 45.041707
        },
        "mouth_right": {
          "x": 55.134878,
          "y": 44.858049
        },
        "nose": {
          "x": 50.183415,
          "y": 38.410732
        },
        "width": 27.560976
      },
      "tag": ""
    }
  ],
  "img_height": 410,
  "img_id": "1e3007cb3d6cfbaed3a1b4135524ed25",
  "img_width": 410,
  "session_id": "76ec7f99a471418fa8862a2138cc589d",
  "url": "http://www.faceplusplus.com/wp-content/themes/faceplusplus/assets/img/demo/1.jpg?v=2"
}

我想从上面的 json 中提取“女性”。 为此,我使用了这个:

 import urllib2
 import io, json
 from bs4 import BeautifulSoup
 data = soup #soup has all the data json
 with open('data.json', 'w') as outfile:
     json.dump(data, outfile, sort_keys = True, indent = 4, ensure_ascii=False)
 #content = json.loads(soup)
 jsonFile = open('data.json', 'r')
 values = json.load(jsonFile)
 jsonFile.close()
 gender = soup['face'][0]['gender']['value']
 print gender

我的代码哪里不正确?


根据你的 json 示例,gender在里面attribute,所以你需要访问它 -

gender = soup['face'][0]['attribute']['gender']['value']

还有,好像values是读回的 json(字典),因此您可能需要使用以下方式访问它values,虽然我不确定你想要实现什么,所以我不能肯定地说。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Python中获取JSON的字段特定值? 的相关文章

随机推荐