Is there a way to configure the python json library to ignore fields having null values ​​when calling json.loads?

python version 2.7

>>> json.loads('{"key":null,"key2":"yyy"}') {u'key2': u'yyy', u'key': None} 

The above default behavior that I want will be the result of {u'key2 ': u'yyy} any suggestions? Thank you so much!

+7
json python
source share
1 answer

You can filter the result after loading:

 res = json.loads(json_value) res = {k: v for k, v in res.iteritems() if v is not None} 

Or you can do it in object_hook called:

 def remove_nulls(d): return {k: v for k, v in d.iteritems() if v is not None} res = json.loads(json_value, object_hook=remove_nulls) 

which will also handle recursive dictionaries.

For Python 3, use .items() instead of .iteritems() to efficiently list the keys and values ​​of a dictionary.

Demo:

 >>> import json >>> json_value = '{"key":null,"key2":"yyy"}' >>> def remove_nulls(d): ... return {k: v for k, v in d.iteritems() if v is not None} ... >>> json.loads(json_value, object_hook=remove_nulls) {u'key2': u'yyy'} >>> json_value = '{"key":null,"key2":"yyy", "key3":{"foo":null}}' >>> json.loads(json_value, object_hook=remove_nulls) {u'key3': {}, u'key2': u'yyy'} 
+12
source share

All Articles