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?
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With