jq not replacing json value with parameter

梦想的初衷 提交于 2020-01-30 05:21:45

问题


test.sh is not replacing test.json parameter values ($input1 and $input2). result.json has same ParameterValue "$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

回答1:


shell variables in jq scripts should be interpolated or passed as arguments via --arg name value:

jq --arg inp1 "$input1" --arg inp2 "$input2" \
'map(if .ParameterKey == "Project" 
    then . + {"ParameterValue" : ($inp1 + "/solution/" + $inp2 + ".result") } 
else . end)' test.json

The output:

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



回答2:


In your jq program, you have quoted "$input1/solution/$input2.result", and therefore it is a JSON string literal, whereas you evidently want string interpolation; you also need to distinguish between the shell variables ($input1 and $input2) on the one hand, and the corresponding jq dollar-variables (which may or may not have the same name) on the other.

Since your shell variables are strings, you could pass them in using the --arg command-line option (e.g. --arg input1 "$input1" if you chose to name the variables in the same way).

You can read up on string interpolation in the jq manual (see https://stedolan.github.io/jq/manual, but note the links at the top for different versions of jq).

There are other ways to achieve the desired results too, but using string interpolation with same-named variables, you'd write:

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

Notice that the above string is NOT itself literally a JSON string. Only after string interpolation does it become so.



来源:https://stackoverflow.com/questions/47374719/jq-not-replacing-json-value-with-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!