【问题标题】:Conditional JSON parse and append条件 JSON 解析和追加
【发布时间】:2021-11-26 07:24:08
【问题描述】:

在下面的多维 JSON 中,我提取了“宽度”和“高度”值,因为我想附加到一个空表/数组上并稍后将它们用于计算。在以下 JSON 上。

[
{
 "frame_id":1, 
 "filename":"bake/IMG_20210930_090024.jpg", 
 "objects": [ 
  {"class_id":0, "name":"brick", "relative_coordinates":{"left_x":1279, "top_y": 991, "width": 922, "height":1164},"relevant":true}
 ] 
}, 
{
 "frame_id":2, 
 "filename":"bake/IMG_20210930_090017.jpg", 
 "objects": [ 
  {"class_id":1, "name":"limestone", "relative_coordinates":{"left_x":1672, "top_y":1536, "width": 651, "height": 623},"relevant":true}
 ] 
}
]

我的代码和结果:

with open('/home/pan/output/result.json') as json_data:
data = json.load(json_data)
for item in data:
for row in item.get('objects', []):
print(row['class_id'], row['relative_coordinates']['width'],row['relative_coordinates']['height'])

0 922 1164
1 651 623       

我的主要问题是我只想显示“class_id”的结果:0 的宽度和高度。 另外,通过控制台或空数组 [] 附加这些值并稍后进行计算的最佳方法是什么?

【问题讨论】:

    标签: python json if-statement parsing


    【解决方案1】:

    只需在您的代码中添加if 条件即可得到如下预期结果:

    data = None
    with open('/home/pan/output/result.json') as json_data:
        data = json.load(json_data)
    co_ordinates = []
    for item in data:
        for row in item.get('objects', []):
            if row['class_id'] == 0:
                co_ordinates.append(row['relative_coordinates']['width'])
                co_ordinates.append(row['relative_coordinates']['height'])
                break
                
    print (co_ordinates)
    

    输出:

    [922, 1164]
    

    【讨论】:

      【解决方案2】:

      您可以通过逐个查看字典和列表来获取数据。

      width = -1
      height = -1
      for item in data:
          if item['objects'][0]['class_id'] == 0:
              width = item['objects'][0]['relative_coordinates']['width']
              height ​= item['objects'][0]['relative_coordinates']['height']
              break
      

      【讨论】:

      • 这根本不是真的。我检查了外部列表中的所有项目。
      【解决方案3】:

      你可以试试这个:

      value_list = []
      with open('result.json') as json_data:
          data = json.load(json_data)
          for item in data:
              for row in item.get('objects', []):
                  if row['class_id'] == 0:
                      print(row['class_id'], row['relative_coordinates']['width'], row['relative_coordinates']['height'])
                      value_list.append(row['relative_coordinates']['width'])
                      value_list.append(row['relative_coordinates']['height'])
      
      print(value_list)
      
      

      输出:

      0 922 1164
      [922, 1164]
      

      【讨论】:

      • 最好将循环 for item in data 分开,这样我们就不必在从中获取数据后保持文件打开。
      • 我只是尽量保持代码不变,这就是为什么这样写,否则我们可以使用变量读取文件并使用该变量执行其余操作。 :)
      猜你喜欢
      • 2012-03-06
      • 2011-04-25
      • 1970-01-01
      • 1970-01-01
      • 2022-08-20
      • 1970-01-01
      • 1970-01-01
      • 2017-01-02
      • 2021-10-17
      相关资源
      最近更新 更多