溫馨提示×

json怎么去掉null字段

小億
342
2024-02-05 14:07:23
欄目: 編程語言

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

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女