You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何删除JSON文件中所有category为traffic sign的区块

删除JSON中所有category为"traffic sign"的区块

先明确常见的JSON结构(以数组类型为例)

你的JSON内容大概率类似这种格式:

[
  {
    "category": "building",
    "id": 1,
    "content": "sample content"
  },
  {
    "category": "traffic sign",
    "id": 2,
    "content": "sample content"
  },
  {
    "category": "tree",
    "id": 3,
    "content": "sample content"
  }
]

方法1:Python脚本(新手友好)

直接用以下代码,替换对应文件名即可完成处理:

import json

# 读取原始JSON文件
with open('your_source_file.json', 'r', encoding='utf-8') as f:
    raw_data = json.load(f)

# 过滤掉category为"traffic sign"的条目
filtered_data = [item for item in raw_data if item.get('category') != 'traffic sign']

# 将处理后的内容写入新文件
with open('filtered_result.json', 'w', encoding='utf-8') as f:
    json.dump(filtered_data, f, indent=2, ensure_ascii=False)
  • 把your_source_file.json换成你的源文件名,filtered_result.json是处理后的输出文件
  • 如果你的JSON是嵌套结构(比如外层有{"items": [/* 条目数组 */]}),只需调整代码:
    # 读取后先提取嵌套数组
    raw_data = json.load(f)['items']
    # 过滤后重新组装结构
    final_data = {"items": filtered_data}
    # 写入时使用final_data
    json.dump(final_data, f, indent=2, ensure_ascii=False)
    

方法2:jq命令行工具(快速批量处理)

如果你的系统安装了jq(Linux/macOS默认自带,Windows可直接下载安装),在终端执行对应命令即可:

# 针对数组结构的JSON
jq 'map(select(.category != "traffic sign"))' your_source_file.json > filtered_result.json

# 针对嵌套结构(比如外层有items键)
jq '.items |= map(select(.category != "traffic sign"))' your_source_file.json > filtered_result.json

内容的提问来源于stack exchange,提问作者Aravind Suresh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 21:52:10