如何使用jq为JSON文件条件式添加新的键值对?
解决方法
你可以用jq的map()遍历数组对象,结合条件判断来添加baz字段,以下是两种实用实现方式:
基础条件判断写法
通过if/else明确逻辑,可读性更强:
jq 'map(. + {baz: (if .foo != null and .bar != null then "true" else "false" end)})' input.json
简洁写法
利用jq的布尔运算转字符串特性,代码更紧凑:
jq 'map(. + {baz: ((.foo != null) and (.bar != null) | tostring)})' input.json
执行效果
针对你提供的输入JSON,执行后输出结果为:
[ { "foo": "fooValue", "bar": "barValue", "baz": "true" }, { "foo": null, "bar": null, "baz": "false" } ]
细节说明
map():遍历JSON数组中的每一个对象. + {baz: ...}:将新字段baz合并到原对象中- 条件核心:
(.foo != null) and (.bar != null)确保两个字段都不为null时返回布尔值true,再通过tostring转成你需要的字符串类型"true"/"false" - 若要直接修改原文件(in-place编辑),可添加
-i参数(jq 1.5及以上版本支持):jq -i 'map(. + {baz: ((.foo != null) and (.bar != null) | tostring)})' input.json
内容的提问来源于stack exchange,提问作者Jengels
相关产品推荐
相关产品推荐

