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

如何使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 16:23:15