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!
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.
The dump() method is used when the Python objects have to be stored in a file. The dumps() is used when the objects are required to be in string format and is used for parsing, printing, etc, . The dump() needs the json file name in which the output has to be stored as an argument.
1. json. dump() method used to write Python serialized object as JSON formatted data into a file. json. dumps() method is used to encodes any Python object into JSON formatted String.
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'}
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