我有一个包含此数据的JSON文件
{
"in_reply_to_screen_name": null,
"favorited": false,
"id_str": "92",
"entities": {
"user_mentions": [],
"symbols": [],
"urls": [],
"hashtags": [
{
"indices": [0,8]
}
]
},
"geo": null,
"user": {
"verified": false,
"notifications": null,
"profile_sidebar_border_color": "FFFFFF",
"geo_enabled": true,
"profile_background_tile": true,
"url": null,
"id": 278,
"default_profile": false,
"lang": "pt",
"location": null,
"translator_type": "none",
"protected": false
},
"id": 92,
"in_reply_to_status_id_str": null,
"in_reply_to_status_id": null,
"created_at": "Tue Oct",
"is_quote_status": false,
"text": "This is a vdd",
"truncated": false,
"retweeted": false
}
如何使用Python删除包含null,false和true的任何键值对?
这些值可以出现在数据结构的各个级别中。
答案 0 :(得分:4)
通过解码,递归处理对象,再次编码为JSON。
我喜欢使用single dispatch来执行此类任务:
from functools import singledispatch
@singledispatch
def remove_null_bool(ob):
return ob
@remove_null_bool.register(list)
def _process_list(ob):
return [remove_null_bool(v) for v in ob]
@remove_null_bool.register(dict)
def _process_list(ob):
return {k: remove_null_bool(v) for k, v in ob.items()
if v is not None and v is not True and v is not False}
data = json.load(source)
json.dump(dest, remove_null_bool(data))
我使用is not False
等来测试确切的对象。如果我使用v not in {None, False, True}
,那么整数值0
和1
也会被删除,因为False
和True
分别等于这些值。
针对加载到data
的示例进行演示:
>>> print(json.dumps(remove_null_bool(data), indent=4, sort_keys=True))
{
"created_at": "Tue Oct",
"entities": {
"hashtags": [
{
"indices": [
0,
8
]
}
],
"symbols": [],
"urls": [],
"user_mentions": []
},
"id": 92,
"id_str": "92",
"text": "This is a vdd",
"user": {
"id": 278,
"lang": "pt",
"profile_sidebar_border_color": "FFFFFF",
"translator_type": "none"
}
}