json - Remove item in list of dictionaries if value is empty, "null" or None in Python -


i have json object contains sorts of unnecessary values "null", "", none. i'd remove whole object if contains such value.

>>> json.dumps(event, indent=4) "event" = {     "status": "completed",       "datavalues": [     {         "key": "wiidcsq5pdq",         "value": "25"     },     {         "key": "rsz4gqzwpwu",         "value": "null"     },     {         "key": "l7ao70bcrbp",         "value": ""     },     {         "key": "gy6pxrwdthm",         "value": "null"     },     {         "key": "x1708y0c4c7",         "value": false     }     ] } 

my failed attempts:

no_values = ["null", "", none]  # no changes/deletions: [elem elem in event['datavalues'] if elem['value'] not in no_values]  # typeerror: argument of type 'bool' not iterable [elem elem in event['datavalues'] if any(s in elem['value'] s in no_values] 

how can so?

this works me, store data in variable , evaluate using first list comprehension. note i'm using set of ignored_values, faster:

in [12]: import json  in [13]: json_text = """{     "status": "completed",       "datavalues": [     {         "key": "wiidcsq5pdq",         "value": "25"     },     {         "key": "rsz4gqzwpwu",         "value": "null"     },     {         "key": "l7ao70bcrbp",         "value": ""     },     {         "key": "gy6pxrwdthm",         "value": null     },     {         "key": "x1708y0c4c7",         "value": false     }     ] }"""  in [14]: data = json.loads(json_text)  in [15]: ignored_values = set(["null", "", none])  in [16]: [elem elem in data['datavalues'] if elem['value'] not in ignored_values] out[16]:  [{u'key': u'wiidcsq5pdq', u'value': u'25'},  {u'key': u'x1708y0c4c7', u'value': false}] 

Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -