Home > OS >  Reading values from a key within a Directory within a List from a JSON file using Python
Reading values from a key within a Directory within a List from a JSON file using Python

Time:02-13

I've got a rather ML ugly JSON file that I'm trying to pull values from.

Below is the first entry on the list: [ {"ID":"ckzjqmtvf3ltd0z7yhogt3ttm", "DataRow ID":"ckzjq9ry03hfp0zux8xwkhkvv", "Label":{"objects": [{"featureId":"ckzjqnrn600012469dfbkfr1q", "schemaId":"ckzjqkttm3m8v0z78e7rdbkda", "color":"#1CE6FF", "title":"Weed", "value":"weed", "bbox":{"top":1003, "left":810, "height":848, "width":881}, {"featureId":"ckzjqo6iy000724690onwpxax", "schemaId":"ckzjqkttm3m8v0z78e7rdbkda", "color":"#1CE6FF", "title":"Weed", "value":"weed", "bbox"{"top":1780, "left":410, "height":264, "width":254}, {"featureId":"ckzjqobrv000a24697tc84nrr", "schemaId":"ckzjqkttm3m8v0z78e7rdbkda", "color":"#1CE6FF", "title":"Weed", "value":"weed", "bbox":{"top":1060, "left":1799, "height":471, "width":523},]

I am trying to extract the title and bbox information.

I have tried data["Label"][0]["title"], but I get:

KeyError: 0

Any help would be amazing!

CodePudding user response:

Problem is in data itself, because json is not properly closed. I had to remove "," and add "]". After that data.json was valid.

import json

with open("data.json") as file:
    data = json.load(file)

    objects = data[0]["Label"]["objects"]
    for object in objects:
        title = object["title"]
        bbox = object["bbox"]
        print(title)
        print(bbox)

CodePudding user response:

Code to read title and bbox information of all items in json file:

import json

with open("data.json") as file:
    data = json.load(file)

for item in data:
    objects = item['Label']['objects']
    for obj in objects:
        title = obj['title']
        bbox = obj['bbox'] 
  • Related