繁体   English   中英

在 Python 中读取 JSON 索引

[英]Read JSON index in Python


我想用python读取一个json文件,如下所示:

{
  "id": "27147e64-9ef5-42d8-b32e-b46b19071ee3b84e0e07-669e-4a10-8124-8e0d71a08e7e",
  "image": "img0171.png",
  "width": 640,
  "height": 480,
  "tags": [
    {
      "name": "becks_long_neck",
      "parent": null,
      "id": "b2d59c98-0bdc-4d13-ad1b-9d4ab5bc1fb3",
      "color": "#e62921",
      "type": "bounding_box",
      "pos": {
        "x": 387,
        "y": 310.06667073567706,
        "w": 62.666666666666686,
        "h": 38.219034830729186
      }
    },
    {
      "name": "becks_long_neck",
      "parent": null,
      "id": "75635f60-e6b9-4408-89fb-ed435355dac6",
      "color": "#e62921",
      "type": "bounding_box",
      "pos": {
        "x": 358.5,
        "y": 354.06667073567706,
        "w": 40.833333333333314,
        "h": 31.666666666666686
      }
    }
  ]
}

当我想访问第二个名字时,我会尝试这样的操作:

for dictionary in datastore:
    filename = dictionary['image']
    tag = dictionary['tags'][0]['name']
    if(dictionary['tags'][1]['name']):
        tag2 = dictionary['tags'][1]['name']
    print(tag)
    x = dictionary['tags'][0]['pos']['x']
    print(x)
    y = dictionary['tags'][0]['pos']['y']
    print(y)
    w = dictionary['tags'][0]['pos']['w']
    print(w)
    h = dictionary['tags'][0]['pos']['h']
    print(h)

但告诉我这个错误:

Traceback (most recent call last):
  File "json_to_txt.py", line 65, in <module>
    if(dictionary['tags'][1]['name']):
IndexError: list index out of range

如何访问第二个“名称”对象?

您不需要明确定义每个单独的变量,例如tagtag2 .. 等。 而是将此操作留给循环,例如通过将循环索引结构的当前顺序从dictionary[datastore]更改为datastore[dictionary]使其动态地像下面的情况一样:

import json
s = '{"id": "27147e64-9ef5-42d8-b32e-b46b19071ee3b84e0e07-669e-4a10-8124-8e0d71a08e7e","image": "img0171.png","width": 640,"height": 480,"tags": [{"name": "becks_long_neck","parent": null,"id": "b2d59c98-0bdc-4d13-ad1b-9d4ab5bc1fb3","color": "#e62921","type": "bounding_box","pos": {"x": 387,"y": 310.06667073567706,"w": 62.666666666666686,"h": 38.219034830729186}},{"name": "becks_long_neck","parent": null,"id": "75635f60-e6b9-4408-89fb-ed435355dac6","color": "#e62921","type": "bounding_box","pos": {"x": 358.5,"y": 354.06667073567706,"w": 40.833333333333314,"h": 31.666666666666686}}]}'

datastore = json.loads(s)
i=0
for dictionary in datastore:
      if dictionary == 'image':
            filename = datastore[dictionary]         
      if dictionary == 'tags':
            tag = datastore[dictionary]
            for dictionary in tag:
                  print("tag_name",i,tag[i]['name'])
                  i+=1

>>>
tag_name 0 becks_long_neck
tag_name 1 becks_long_neck

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM