如何基于color键值对条件删除JSON数组中不符合条件的对象?
过滤JSON数组,仅保留指定条件的对象
针对你需要删除markers数组中color值不等于2的对象的需求,以下是两种可行实现方案:
一、Windows环境无需Python的处理方法
1. PowerShell(系统自带,零额外安装)
Windows默认自带PowerShell,可直接用它完成JSON过滤:
# 读取input.json文件内容并转为JSON对象 $jsonContent = Get-Content -Path "input.json" -Raw | ConvertFrom-Json # 筛选markers数组中color等于2的对象,覆盖原数组 $jsonContent.markers = $jsonContent.markers | Where-Object { $_.color -eq 2 } # 将处理后的内容写入output.json,-Depth参数确保嵌套结构不被截断 $jsonContent | ConvertTo-Json -Depth 10 | Set-Content -Path "output.json"
执行后output.json将只保留符合条件的对象,无空项残留。
2. jq工具(轻量专业JSON处理工具)
若你愿意安装轻量工具,jq是更简洁的选择:
- 下载对应Windows版本的jq程序,将其所在路径添加到系统环境变量
PATH中 - 在命令提示符(CMD)或PowerShell中执行:
jq '.markers |= map(select(.color == 2))' input.json > output.json
该命令直接对markers数组做筛选,将结果写入新文件。
二、Python实现方案
若后续安装Python,可使用以下脚本完成处理:
import json # 读取输入JSON文件 with open('input.json', 'r', encoding='utf-8') as input_file: data = json.load(input_file) # 筛选markers数组,仅保留color值为2的对象 data['markers'] = [item for item in data['markers'] if item.get('color') == 2] # 将处理后的数据写入输出文件,保持原格式缩进 with open('output.json', 'w', encoding='utf-8') as output_file: json.dump(data, output_file, indent=2, ensure_ascii=False)
脚本使用列表推导式直接过滤数组,item.get('color')可避免因对象缺少color键导致的报错,最终输出格式与原JSON一致。
内容的提问来源于stack exchange,提问作者Tom S
相关产品推荐
相关产品推荐

