如何使用jq或Python移除JSON中的指定comment键
移除JSON中所有"comment"键的解决方案
我知道你现在需要清理从Red Hat Satellite导出的Puppet类JSON数据,把所有的comment键都删掉对吧?这里给你准备了jq和Python两种实现方式,都能轻松搞定这个需求。
使用jq快速处理
jq是处理JSON的命令行神器,一行命令就能完成任务:
jq 'del(..|.comment?)' input.json > output.json
- 把你的原始JSON内容保存到
input.json文件中 - 运行上述命令后,清理好的JSON会被写入
output.json里 - 命令解释:
..会递归遍历JSON的所有层级,.comment?匹配存在的comment键,del()负责删除这些匹配到的键,完美适配你的嵌套结构。
使用Python脚本处理
如果需要把这个逻辑集成到Python工作流里,下面的脚本可以帮你递归清理所有comment键,还能保持JSON的格式化缩进:
import json def remove_comments(obj): if isinstance(obj, dict): # 过滤掉comment键,同时递归处理每个值 return {key: remove_comments(value) for key, value in obj.items() if key != "comment"} elif isinstance(obj, list): # 列表元素逐个递归处理 return [remove_comments(item) for item in obj] else: # 非容器类型直接返回原值 return obj # 读取原始JSON文件 with open('input.json', 'r') as input_file: raw_data = json.load(input_file) # 执行清理操作 cleaned_data = remove_comments(raw_data) # 将结果写入新文件,保持缩进格式 with open('output.json', 'w') as output_file: json.dump(cleaned_data, output_file, indent=2)
- 运行脚本后,
output.json里的内容就是你期望的无comment键的JSON结构 - 这个脚本会处理所有嵌套层级的字典,不管
comment在哪个位置都能被删掉,同时保留其他所有数据结构不变。
内容的提问来源于stack exchange,提问作者Magic Thighs
相关产品推荐
相关产品推荐

