JSON annotations error “string indices must be integers”

Wrote a function to parse COCO JSON. How to solve error? a sample file_name here is : hard_hat_workers2819_png.rf.6870e9b0e6f5cd67d581d9d6185124e6.jpg The name of the file can’t be changed as the dataset is huge. What should I do?

[enter image description here][1]

def get_board_dicts(imgdir):
    json_file = imgdir+"/_annotations.coco.json" #Fetch the json file
    with open(json_file) as f:
        dataset_dicts = json.load(f) #loads(jsonStr)
    for i in dataset_dicts:
        filename = i['file_name'] 
        i['file_name'] = imgdir+"/"+filename 
        for j in i["annotations"]:
            j["bbox_mode"] = BoxMode.XYWH_ABS #Setting the required Box Mode
            j["category_id"] = int(j["category_id"])
    return dataset_dicts 


---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)
<ipython-input-21-3c960c9b4cee> in <module>()
      1 #Visualizing the Train Dataset
----> 2 dataset_dicts = get_board_dicts("HardHat_COCO/train")
      3 #Randomly choosing 3 images from the Set
      4 for d in random.sample(dataset_dicts, 3):
      5     img = cv2.imread(d["file_name"])

<ipython-input-20-a32bcb391fe9> in get_board_dicts(imgdir)
      7         dataset_dicts = json.load(f) #loads(jsonStr)
      8     for i in dataset_dicts:
----> 9         filename = i['file_name']
     10         i['file_name'] = imgdir+"/"+filename
     11         for j in i["annotations"]:

TypeError: string indices must be integers 


  #samples from COCO JSON file:
"images": [
        {
            "id": 0,
            "license": 1,
            "file_name": "hard_hat_workers2819_png.rf.6870e9b0e6f5cd67d581d9d6185124e6.jpg",
            "height": 416,
            "width": 416,
            "date_captured": "2021-08-31T14:27:07+00:00"
        },
        {
            "id": 1,
            "license": 1,
            "file_name": "hard_hat_workers239_png.rf.68144af0d963cc745832ccbf69cd93ec.jpg",
            "height": 416,
            "width": 416,
            "date_captured": "2021-08-31T14:27:07+00:00"
        },

Answer

Its difficult to tell, but you might mean this:

for i in dataset_dicts['images']:
    filename = i['file_name']
    ...