1

In a Python script I run json_decoded = json.load(file) that results in the following JSON data:

json_decoded = {
  "data": {
    "keyA": [
      {
        "subkeyA1": "valueA1",
        "subkeyA2": "valueA2"
      },
      {
        "subkeyA3": ""
      }
    ],
    "keyB": []
  }
}

I would like to remove all the [] and "" ("empty") key-value pairs so to have:

json_decoded = {
  "data": {
    "keyA": [
      {
        "subkeyA1": "valueA1",
        "subkeyA2": "valueA2"
      }
    ]
  }
}

How can I have that?

Note: I am pretty new to Python (v2.7.3).

Backo
  • 18,291
  • 27
  • 103
  • 170

1 Answers1

2

You can use recursion to traverse the structure:

json_decoded = {'data': {'keyA': [{'subkeyA1': 'valueA1', 'subkeyA2': 'valueA2'}, {'subkeyA3': ''}], 'keyB': []}}
def remove_empty(d):
  final_dict = {}
  for a, b in d.items():
     if b:
       if isinstance(b, dict):
         final_dict[a] = remove_empty(b)
       elif isinstance(b, list):
         final_dict[a] = list(filter(None, [remove_empty(i) for i in b]))
       else:
         final_dict[a] = b
  return final_dict

print(remove_empty(json_decoded))

Output:

{'data': 
  {'keyA': 
     [{'subkeyA1': 'valueA1', 
       'subkeyA2': 'valueA2'}
    ]
  }
}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102