Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude empty/null values from JSON serialization

Tags:

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?

like image 601
simao Avatar asked Nov 23 '10 11:11

simao


People also ask

How do I ignore null values in JSON object?

You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.

How do you tell Jackson to ignore a field during Deserialization if its value is null?

Jackson default include null fields 1.2 By default, Jackson will include the null fields. To ignore the null fields, put @JsonInclude on class level or field level.


1 Answers

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.

like image 199
Chris Morgan Avatar answered Sep 22 '22 03:09

Chris Morgan