jq 没有用参数替换 json 值

jq not replacing json value with parameter

test.sh 不会替换 test.json 参数值($input1 和 $input2)。 result.json 具有相同的参数值“$input1/solution/$input2.result”

 [
    {
      "ParameterKey": "Project",
      "ParameterValue": [ "$input1/solution/$input2.result" ]
     }
    ]

test.sh

#!/bin/bash
input1="test1"
input2="test2"
echo $input1
echo $input2
cat test.json | jq 'map(if .ParameterKey == "Project"           then . + {"ParameterValue" : "$input1/solution/$input2.result" }             else .             end           )' > result.json

shell jq 脚本中的变量应通过 --arg name value:

插入或作为参数传递
jq --arg inp1 "$input1" --arg inp2 "$input2" \
'map(if .ParameterKey == "Project" 
    then . + {"ParameterValue" : ($inp1 + "/solution/" + $inp2 + ".result") } 
else . end)' test.json

输出:

[
  {
    "ParameterKey": "Project",
    "ParameterValue": "test1/solution/test2.result"
  }
]

在你的 jq 程序中,你引用了“$input1/solution/$input2.result”,因此它是一个 JSON 字符串文字,而你显然想要字符串插值;您还需要一方面区分 shell 变量($input1 和 $input2),另一方面区分相应的 jq 美元变量(名称可能相同也可能不同)。

由于您的 shell 变量是字符串,您可以使用 --arg 命令行选项传递它们(例如 --arg input1 "$input1" 如果您选择以相同的方式命名变量).

您可以在 jq 手册中阅读有关字符串插值的内容(请参阅 https://stedolan.github.io/jq/manual,但请注意顶部针对不同版本的 jq 的链接)。

还有其他方法可以达到预期的效果,但是使用带有同名变量的字符串插值,你会写:

"\($input1)/solution/\($input2).result" 

请注意,上面的字符串本身并不是 JSON 字符串。只有经过字符串插值后才会这样。