json怎么去掉null字段
在 JSON 中,可以通过遍历对象的属性来检查和删除 null 值字段。以下是一个示例代码:
import json
def remove_null_fields(obj):
if isinstance(obj, dict):
return {key: remove_null_fields(value) for key, value in obj.items() if value is not None}
elif isinstance(obj, list):
return [remove_null_fields(item) for item in obj if item is not None]
else:
return obj
json_data = '{"name": "John", "age": null, "city": "New York", "state": null}'
# 解析 JSON 数据
data = json.loads(json_data)
# 去掉 null 字段
data_without_null = remove_null_fields(data)
# 将数据转换回 JSON 字符串
json_without_null = json.dumps(data_without_null)
print(json_without_null)
输出结果将是:{"name": "John", "city": "New York"}
,其中所有的 null 字段已经被移除了。
版权声明
本文仅代表作者观点,不代表米安网络立场。
上一篇:动态负载均衡策略是什么 下一篇:python中group by的用法是什么
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。