删除特定键值为空的JSON对象(附示例JSON数据)
方法:删除JSON数组中特定键值为空的对象
假设你手里的是像示例这样的DNS记录JSON数组,要移除数组里特定键对应值为空的对象,下面分两种常用编程语言给出具体实现方案:
Python 实现
先把JSON字符串解析成Python的列表和字典,再通过过滤逻辑剔除不符合要求的对象。比如我们要删除A键值为空数组的对象:
import json # 你的原始JSON数据(包含一个空值示例) json_data = ''' [{ "Domain": "google.com", "A": ["172.217.22.46"], "AAAA": ["2a00:1450:4001:81e::200e"], "CAA": ["0 issue \"pki.goog\""], "MX": ["20 alt1.aspmx.l.google.com.", "30 alt2.aspmx.l.google.com.", "10 aspmx.l.google.com.", "40 alt3.aspmx.l.google.com.", "50 alt4.aspmx.l.google.com."], "NS": ["ns1.google.com.", "ns3.google.com.", "ns2.google.com.", "ns4.google.com."], "SOA": ["ns1.google.com. dns-admin.google.com. 189483475 900 900 1800 60"], "TXT": ["\"docusign=05958488-4752-..."] }, { "Domain": "example.com", "A": [], # 这个对象的A值为空,我们要删除它 "AAAA": ["2606:2800:220:1:248:1893:25c8:1946"] }] ''' # 解析JSON为Python列表 data = json.loads(json_data) # 指定要检查的目标键 target_key = "A" # 过滤数组:只保留目标键值不为空的对象 filtered_data = [obj for obj in data if obj.get(target_key, []) != []] # 转换回格式化的JSON字符串(可选操作) filtered_json = json.dumps(filtered_data, indent=2) print(filtered_json)
补充说明:
obj.get(target_key, []):如果对象里没有目标键,默认按空数组处理,你可以根据需求改成None或者其他空值类型- 要是想判断更广义的“空”(比如
None、空字符串、空数组),可以把条件改成if bool(obj.get(target_key))
JavaScript 实现
不管是前端浏览器环境还是Node.js,都可以用数组的filter方法快速处理:
// 原始JSON数据(包含空值示例) const jsonData = [ { "Domain": "google.com", "A": ["172.217.22.46"], "AAAA": ["2a00:1450:4001:81e::200e"], "CAA": ["0 issue \"pki.goog\""], "MX": ["20 alt1.aspmx.l.google.com.", "30 alt2.aspmx.l.google.com.", "10 aspmx.l.google.com.", "40 alt3.aspmx.l.google.com.", "50 alt4.aspmx.l.google.com."], "NS": ["ns1.google.com.", "ns3.google.com.", "ns2.google.com.", "ns4.google.com."], "SOA": ["ns1.google.com. dns-admin.google.com. 189483475 900 900 1800 60"], "TXT": ["\"docusign=05958488-4752-..."] }, { "Domain": "example.com", "A": [], # 空值对象,需要被删除 "AAAA": ["2606:2800:220:1:248:1893:25c8:1946"] } ]; // 指定要检查的目标键 const targetKey = "A"; // 过滤数组 const filteredData = jsonData.filter(obj => { const value = obj[targetKey]; // 针对数组和非数组值分别判断空值:数组看长度,其他值看是否为真 return Array.isArray(value) ? value.length > 0 : !!value; }); console.log(JSON.stringify(filteredData, null, 2));
补充说明:
- 如果需要同时检查多个键的空值情况,可以把判断逻辑改成多条件,比如
return obj.A && obj.MX - 可以根据实际需求调整空值的定义,比如把空字符串也纳入判断范围
通用核心思路
不管用什么编程语言,处理逻辑都逃不开这三步:
- 解析JSON:把JSON字符串转成编程语言的原生数据结构(比如Python的列表/字典、JS的数组/对象)
- 过滤数组:遍历数组里的每个对象,检查指定键的值是否为空,只保留符合要求的对象
- 序列化(可选):把过滤后的原生数据结构转回JSON字符串
内容的提问来源于stack exchange,提问作者Jishan




