skip to Main Content

This is a json file containing several category. What I am trying to achieve is that if the category is traffic sign how to remove the entire section for all category: traffic sign.I want to remove this selected portion for all category=traffic sign

I tried several methods but I couldn’t sort it out, because I am new to json and its structure.

2

Answers


  1. import json

    with open(‘test.json’, ‘r’) as jf:
    jsonFile = json.load(jf)

    print(‘Length of JSON object before cleaning: ‘, len(jsonFile.keys()))

    testJson = {}
    keyList = jsonFile.keys()
    for key in keyList:
    if not key.startswith(‘traffic’):
    print(key)
    testJson[key] = jsonFile[key]

    print(‘Length of JSON object after cleaning: ‘, len(testJson.keys()))

    with open(‘test.json’, ‘w’) as jf:
    json.dump(testJson, jf)

    Login or Signup to reply.
  2. The area you selected is actually an array. We can just use .filter() on it. I can’t see how the JSON file is laid out with the limited view given in the image but assuming that you know how to drill down into the document to the "labels" section I can take it from there.

    data.filter(e=>{if(e.category!=="traffic sign") return true})
    

    The question is tagged as JavaScript but I see a python file in the screenshot. I’m a little confused on what language you want this in. But I’ll assume that that JavaScript tag is correct. That line above will filter the array and return a new array with the undesirable stuff removed. Try the code snippit, notice how the item that is "category":"traffic sign" is missing from the output. Now all you have to do is figure out how to drill into the JSON file to get to "labels" and do some file input and output.

    let data=[
        {
            "category": "traffic sign",
            "attributes": {
                "occluded": false,
                "truncated": false,
                "trafficLightColor":"none"
            },
            "manualShape": true,
            "manualAttributes": true,
            "box2d": {
                "x1": 1254.32445,
                "y1": 426.54642,
                "x2": 1324.43668,
                "y2": 346.43542
            },
            "id": 0
        },
        {
            "category": "not traffic sign",
            "attributes": {
                "occluded": false,
                "truncated": false,
                "trafficLightColor":"none"
            },
            "manualShape": true,
            "manualAttributes": true,
            "box2d": {
                "x1": 1254.32445,
                "y1": 426.54642,
                "x2": 1324.43668,
                "y2": 346.43542
            },
            "id": 0
        }
    ];
    
    console.log(data.filter(e=>{if(e.category!=="traffic sign") return true}));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search