0

I'm attempting to parse the output of a script that takes a parameter and for each parameter pulls some json. I'm parsing with jq. On the command line for one run of the script a command like this one works:

./script_that_produces_json --intput=value | jq '.[] | select(.name=="objecName") | .fieldIWant

I need to run this for a variety of parameters, which I am attempting to read from an array. This is what my code looks like now:

for entry in "${array[@]}"
do
    output=$(./script_that_produces_json --input=$entry | jq '.[] | select(.name=="$entry") | .fieldIWant)'
    print($output)
done

This yields the variable substituted, but there are no quotes around it, which fails when passed to jq. I've been hacking around this with various combinations of quotes with no success.

How do I quote the variable/string correctly such that both the variable is replaced and the quotes are passed?

K. Don
  • 23
  • 1
  • 6
  • `--input="$entry"`, or `"--input=$entry"` -- they're literally the exact same thing. – Charles Duffy Oct 04 '21 at 20:55
  • 1
    See [BashFAQ #50](http://mywiki.wooledge.org/BashFAQ/050). – Charles Duffy Oct 04 '21 at 20:55
  • Also, use `jq --arg entry "$entry"` to make a jq variable `entry` with the same value as the bash variable `entry`. – Charles Duffy Oct 04 '21 at 20:56
  • Ah, apologies let me clarify the question, it is the second parameter, the one passed to jq I need quoted – K. Don Oct 04 '21 at 20:56
  • 2
    After you've used `jq --arg entry "$entry"`, `select(.name==$entry)` is correct inside the jq string -- you want jq syntax, not bash syntax, there. It would only be correct for it to be `"$entry"` if your input JSON has the literal string `"$entry"` in it. – Charles Duffy Oct 04 '21 at 20:57
  • 1
    (btw, I assume you mean `echo "$output"` in place of `print($output)`?) – Charles Duffy Oct 04 '21 at 20:59
  • 1
    Anyhow -- if the above isn't helpful, could you edit the question to include a [mre] that lets your problem be reproduced? Right now nobody but you has `./script_that_produces_json`, so answers can't be tested. – Charles Duffy Oct 04 '21 at 21:01
  • 1
    Thanks for your help, The question has been closed as a duplicate, but using --arg solved it. – K. Don Oct 04 '21 at 21:10

0 Answers0