Remove empty key,pairs from JSON using python

Question:

i have json data

data = 
[
{"A": "1", "C": "", "B": "2", "E": "4", "D": "3"}, 
{"A": "", "C": "6", "B": "5", "E": "7", "D": ""}, 
{"A": "", "C": "", "B": "", "E": "8", "D": ""}, 
{"A": "", "C": "", "B": "9", "E": "", "D": "10"}
]

I want to remove empty key/value using python so that it looks like this

data = 
[
{"A": "1", "B": "2", "E": "4", "D": "3"}, 
{"C": "6", "B": "5", "E": "7"}, {"E": "8"}, 
{"B": "9", "D": "10"}
]
Asked By: Mike

||

Answers:

You can try this:

data = [
  {"A": "1", "C": "", "B": "2", "E": "4", "D": "3"}, 
  {"A": "", "C": "6", "B": "5", "E": "7", "D": ""}, 
  {"A": "", "C": "", "B": "", "E": "8", "D": ""}, 
  {"A": "", "C": "", "B": "9", "E": "", "D": "10"}
 ]
new_data = [{a:b for a, b in i.items() if b} for i in data]

Output:

[{'A': '1', 'B': '2', 'E': '4', 'D': '3'}, {'C': '6', 'B': '5', 'E': '7'}, {'E': '8'}, {'B': '9', 'D': '10'}]
Answered By: Ajax1234
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.