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フィールドが削除されています。