0

1.Need to remove any value in any level of the keys that has a value null
2.Need to remove any chained key that is named key_2.key_c
Should result in the outcome block below.

Original json

{
"key_1": {
    "key_a": 111111},
"key_2": {
    "key_a": "value",
    "key_b": null,
    "key_c": {
        "key_c_a": {
            "key_c_b": "value"}
            },
    "key_d": [{"key_c": "value"}],
}

Outcome

{
"key_1": {
    "key_a": 111111},
"key_2": {
    "key_a": "value",
    "key_d": [{"key_c": "value"}],
}
joepitz1
  • 194
  • 2
  • 12
  • 1. That is not valid json because of the `null` that is not surrounded by quotes. 2. There are lots of questions here that discuss drilling down and working with nested dictionaries (e.g. [here](/q/65971475/843953), [here](/q/50011078/843953), and [here](/q/3405715/843953)). Did you read any of these and try something? What _specifically_ are you having trouble with? – Pranav Hosangadi Feb 17 '23 at 16:29
  • I did, I suppose the problem i am having is once you drill down to through nested keys using a loop how to you del the entire chain of keys? – joepitz1 Feb 17 '23 at 16:36
  • You just delete the top of the chain. That deletes everything under that key. E.g. when you've drilled down into `"key_2"`, such that `d` is now the value of `"key_2"` you can `del d["key_c"]` to delete the entire key – Pranav Hosangadi Feb 17 '23 at 16:45
  • Does this answer your question? [Exclude empty/null values from JSON serialization](https://stackoverflow.com/questions/4255400/exclude-empty-null-values-from-json-serialization) – JonSG Feb 17 '23 at 17:14

1 Answers1

1

You can achieve this by recursively traversing the input JSON object and filtering out the unwanted values:

import json

def filter_json(obj):
    if isinstance(obj, dict):
        new_obj = {}
        for k, v in obj.items():
            if v is None:
                continue
            if k == "key_2":
                new_obj[k] = filter_json({k2: v2 for k2, v2 in v.items() if k2 != "key_c"})
            else:
                new_obj[k] = filter_json(v)
        return new_obj
    elif isinstance(obj, list):
        return [filter_json(elem) for elem in obj]
    else:
        return obj

Usage


json_str = '''
{
  "key_1": {
    "key_a": 111111
  },
  "key_2": {
    "key_a": "value",
    "key_b": null,
    "key_c": {
      "key_c_a": {
        "key_c_b": "value"
      }
    },
    "key_d": [
      {
        "key_c": "value"
      }
    ]
  }
}
'''

json_obj = json.loads(json_str)
filtered_obj = filter_json(json_obj)
godot
  • 3,422
  • 6
  • 25
  • 42