python-3.x 如何从JSON文件中的一个嵌套字典中取回值

dfuffjeb  于 2022-12-24  发布在  Python
关注(0)|答案(1)|浏览(168)

我是Python和JSON的新手。我遇到了这个问题,我无法打印出“标签”的值。它位于嵌套字典“结果”下。
我在data ['result']中为i尝试的代码:print(“值:“,i ['值'])

values = i['value']

        print("X:", values['x'])
        print("Y:", values['y'])
        print("Width:", values['width'])
        print("Height:", values['height'])

Output from the above code

However when i try to do print("labels:", values['labels'])

        it return a keyerror: 'labels'


        for item in values:
             print(item)

这是显示的输出
x y宽度高度旋转x y宽度高度旋转标签
我可以问一下我如何打印出“标签”值吗?
json文件如下所示:

{
  "id": 9,
  "created_username": "",
  "created_ago": "3\u00a0weeks, 3\u00a0days",
  "completed_by": {
    "id": 1,
    "first_name": "",
    "last_name": "",
    "email": ""
  },
  "task": {
    "id": 1,
    "data": {
      "image": "/data/upload/2/adf8540d-2-33.png"
    },
    "meta": {},
    "created_at": "2022-11-21T14:52:22.478537Z",
    "updated_at": "2022-11-22T12:51:18.105745Z",
    "is_labeled": true,
    "overlap": 1,
    "inner_id": 1,
    "total_annotations": 1,
    "cancelled_annotations": 0,
    "total_predictions": 0,
    "comment_count": 0,
    "unresolved_comment_count": 0,
    "last_comment_updated_at": null,
    "project": 2,
    "updated_by": 1,
    "file_upload": 70,
    "comment_authors": []
  },
  "result": [
    {
      "original_width": 512,
      "original_height": 512,
      "image_rotation": 0,
      "value": {
        "x": 50.898958419872464,
        "y": 44.0069438675168,
        "width": 2.397222452993284,
        "height": 2.0975696463691196,
        "rotation": 0
      },
      "id": "pgaiV8NjWC",
      "from_name": "rect",
      "to_name": "image",
      "type": "rectangle",
      "origin": "manual"
    },
    {
      "original_width": 512,
      "original_height": 512,
      "image_rotation": 0,
      "value": {
        "x": 50.898958419872464,
        "y": 44.0069438675168,
        "width": 2.397222452993284,
        "height": 2.0975696463691196,
        "rotation": 0,
        "labels" [
          "LM"*
        ]
      },
      "id": "pgaiV8NjWC",
      "from_name": "labels",
      "to_name": "image",
      "type": "labels",
      "origin": "manual"
    }
  ],
  "was_cancelled": false,
  "ground_truth": false,
  "created_at": "2022-11-22T12:51:18.001777Z",
  "updated_at": "2022-11-22T12:51:18.001777Z",
  "lead_time": 21.556,
  "project": 2,
  "parent_prediction": null,
  "parent_annotation": null
}
62lalag4

62lalag41#

使用json模块

import json

dict = json.load(json_filename)

然后你应该通过字典键来访问这些值。注意结果值是一个列表。因此索引1是必要的。

values = dict['result'][1]['value']
print("X:", values['x'])

相关问题