Search code examples
jsonpython-3.xdata-manipulationjsonfield

Restructure json data


I have a JSON with following structure:

    {
    "id": 2,
    "image_id": 2,
    "segmentation": [
        [
            913.0,
            659.5,
            895.0,
        ],
        [   
            658.5,
            875.0,
            652.5,
            659.5
        ],
    ],
    "iscrowd": 0,
    "bbox": [
        4.5,
        406.5,
        1098.0,
        1096.0
    ],
    "area": 579348.0,
    "category_id": 0
},

Now I need to split each entry it into two separate entries, like these:

    {
    "id": 2,
    "image_id": 2,
    "segmentation": [
        [
            658.5,
            875.0,
            652.5,
            659.5
        ],
    ],
    "iscrowd": 0,
    "bbox": [
        4.5,
        406.5,
        1098.0,
        1096.0
    ],
    "area": 579348.0,
    "category_id": 0
    },
    {
    "id": 3,
    "image_id": 2,
    "segmentation": [
        [
            913.0,
            659.5,
            895.0,
        ],
    ],
    "iscrowd": 0,
    "bbox": [
        4.5,
        406.5,
        1098.0,
        1096.0
    ],
    "area": 579348.0,
    "category_id": 0
},

So that each new entry has the same image_id and iscrowd, bbox, area & category_id as the original entry, however gets new (incremental) id, and has only one segmentations:[] . So if the original entry had 15 segmentations, the code would split it into 15 entries with unique IDs.

Any tips how? I have found some posts on how to merge based on key value, but not how to split.


Solution

  • import json
    
    new_json = []
    ids = 0
    
    
    for i in original_json:
        segms = i["segmentation"]
        for j in segms:
            dummy = {}
            for k in i:
                dummy[k] = i[k]
            dummy["id"] = ids
            dummy["segmentation"] = j
            ids+=1
            new_json.append(dummy)
    
    with open("new_json_file.json", 'w') as f:
        json.dump(new_json, f)
    

    Hope this helps