有没有办法配置python json库来忽略调用json.loads时具有空值的字段?

时间:2022-06-11 06:51:21

python version 2.7

python版本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 becomes {u'key2': u'yyy'} any suggestions? thanks a lot!

以上是我想要的默认行为,结果变为{u'key2':u'yyy'}任何建议?非常感谢!

1 个解决方案

#1


12  

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:

或者你可以在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.

对于Python 3,使用.items()而不是.iteritems()来有效地枚举字典的键和值。

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'}

#1


12  

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:

或者你可以在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.

对于Python 3,使用.items()而不是.iteritems()来有效地枚举字典的键和值。

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'}