Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

json

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!

like image 357
Bobo Avatar asked Jan 28 '14 17:01

Bobo


People also ask

How do you ignore null fields in JSON response?

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.

What is JSON dump Python?

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.

What is JSON dump and dumps?

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.


1 Answers

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'}
like image 121
Martijn Pieters Avatar answered Oct 14 '22 15:10

Martijn Pieters