Home > Software engineering >  Delete null values from Json
Delete null values from Json

Time:01-05

for a multilevel nested Json what will be the approach to delete all the null values retaining the other data

json = {
    "Object": {
        "Name": "John",
        "Age": "23",
        "Des": "SE",
        "tech": {
            "Primary": ".net",
            "secondary": "java",
            "current": {
                "first": "Angular",
                "second": "Spring",
                "interests": {
                    "First": "FED",
                    "Second": null,
                    "value": {
                        "First": "High",
                        "Second": null
                    }
                }
            }
        }
    }

please assist me on this. Thanks

CodePudding user response:

You can use a function to build a dictionary basically containing all key: value items where value != None, which recurses into dict values. A dict comprehension allows to encode it as a single statement:

def remove_null_values(d: dict) -> dict:
    return {
        key: remove_null_values(value) if isinstance(value, dict) else value
        for key, value in d.items()
        if value != None
    }
  •  Tags:  
  • Related