Is there a way to config Python's JSON library to ignore fields that have null values when calling json.loads()?

json, python

Solution

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 this in the `object_hook` callable:

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 handle recursive dictionaries too.

For Python 3, use `.items()` instead of `.iteritems()` to efficiently enumerate the keys and values of the 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'}

Problem

Python version 2.7 ``` >>> json.loads('{"key":null,"key2":"yyy"}') {u'key2': u'yyy', u'key': None} ``` The above is the default behaviour. What I want is the result to become: ``` {u'key2': u'yyy'} ``` Any suggestions? Thanks a lot!

Original source