pythonjsonsimplejson

Exclude empty/null values from JSON serialization


I am serializing multiple nested dictionaries to JSON using Python with simplejson.

Is there any way to automatically exclude empty/null values?

For example, serialize this:

 {
     "dict1" : {
     "key1" : "value1",
     "key2" : None
     }
 }

to

 {
     "dict1" : {
     "key1" : "value1"
     }
 }

When using Jackson with Java you can use Inclusion.NON_NULL to do this. Is there a simplejson equivalent?


Solution

  • def del_none(d):
        """
        Delete keys with the value ``None`` in a dictionary, recursively.
    
        This alters the input so you may wish to ``copy`` the dict first.
        """
        # For Python 3, write `list(d.items())`; `d.items()` won’t work
        # For Python 2, write `d.items()`; `d.iteritems()` won’t work
        for key, value in list(d.items()):
            if value is None:
                del d[key]
            elif isinstance(value, dict):
                del_none(value)
        return d  # For convenience
    

    Sample usage:

    >>> mydict = {'dict1': {'key1': 'value1', 'key2': None}}
    >>> print(del_none(mydict.copy()))
    {'dict1': {'key1': 'value1'}}
    

    Then you can feed that to json.