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

使用Bash脚本更新含变量数组的JSON时遇错误求助

问题原因

报错jq: invalid JSON text passed to --argjson是因为你传给--argjson的变量内容不是合法的JSON格式:

  • egress_value='[test,test1]' 和 egress_protocol='[http,https]' 中的字符串元素(test、test1、http、https)没有用双引号包裹,不符合JSON语法规范——JSON字符串必须以双引号界定。
  • egress_port='[80,443]' 是合法的JSON数字数组,但你期望最终输出的port是字符串类型(比如"80"),后续需要额外转换。
解决方案

方案1:修正变量为合法JSON格式

直接把变量里的字符串元素加上双引号,同时在jq处理时将port转为字符串:

egress_port='[80,443]'
egress_value='["test","test1"]'
egress_protocol='["http","https"]'

cat test.json |
jq  --argjson port "$egress_port" \
   --argjson value "$egress_value" \
   --argjson protocol "$egress_protocol" \
   '.environments.egress = ([$port, $value, $protocol] | transpose |
   map ({port: .[0]|tostring, type: "external", value: .[1], protocol: .[2]}))'

方案2:用普通字符串变量+split处理(更符合bash习惯)

如果不想写JSON格式的变量,可以用逗号分隔的普通字符串,在jq中通过split分割成数组:

egress_port='80,443'
egress_value='test,test1'
egress_protocol='http,https'

cat test.json |
jq --arg port_str "$egress_port" \
   --arg value_str "$egress_value" \
   --arg proto_str "$egress_protocol" \
   '
   ($port_str | split(",") | map(tonumber)) as $ports
   | ($value_str | split(",")) as $values
   | ($proto_str | split(",")) as $protocols
   | .environments.egress = ([$ports, $values, $protocols] | transpose | map({
       port: .[0]|tostring,
       type: "external",
       value: .[1],
       protocol: .[2]
     }))
   '

两种方案都能生成你期望的JSON结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 20:37:06