在 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 字段已经被移除了。