Home > OS >  Conditional JSON parse and append
Conditional JSON parse and append

Time:10-06

On the multidimensional JSON below i had extracted the "width" and "height" values as i want to append on an empty table/array and use them later for calculations. On the following 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}
 ] 
}
]

My code and result:

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       

My main question would be that i would like to show the results only for "class_id":0 for width and height. Also whats the best way to append those values through the console or an empty array[] and make calculations later?

CodePudding user response:

You can try this:

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)

Output:

0 922 1164
[922, 1164]

CodePudding user response:

You get to your data by slogging through the dicts and lists one by one.

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