Pravin Mishra
Pravin Mishra

Reputation: 317

Remove objects in nested json response python

This json file has nested "dbg_info","status","start_element","num_elements" etc as object.I want to recursively go through json and recursivily remove objects with the name mentioned in this list.["dbg_info","status","start_element","num_elements"].In python.

My Json:

{
    "status": "OK",
    "start_element": 0,
    "num_elements": 100,
   
        }
    ]
}

How to remove nested json elements?.I am not able to set the logic for the same. Thankyou

Upvotes: 1

Views: 528

Answers (1)

deadshot
deadshot

Reputation: 9071

You can use recursive function

import json

d = json.loads(json_data)
lst = ["dbg_info","status","start_element","num_elements"]

def fun(d, lst=[]):
    if isinstance(d, dict):
        for k, v in list(d.items()):
            d.pop(k) if k in lst else fun(v)
    elif isinstance(d, list):
        map(fun, d)

fun(d, lst)

Upvotes: 2

Related Questions