0

I am trying parse the value of a json property whose key has hyphens in it.

  1. I read the json content into a variable using sub shell commands srcJson=$(someshellcommand)

  2. I pipe the variable into jq read operation (and also pipe it further to sed for some changes - but beside the point) value=$(echo $srcJson | jq .root.parent.$srcKey | sed -e 's/\\\"/\"/g' -e 's/^.//g' -e 's/.$//g')

I am running the code inside a bash script on mac.

This approach works just fine if the $srcKey variable does NOT have any hyphens in it, but breaks with the following error if it has hyphens jq: error: Part1OfHypenatedKey/0 is not defined at <top-level> jq: error: Part2OfHypenatedKey/0 is not defined at <top-level>

Tried putting just the variable with hyphens inside quotes - didnt make a difference value=$(echo $srcJson | jq .root.parent."$srcKey" | sed -e 's/\\\"/\"/g' -e 's/^.//g' -e 's/.$//g')

Tried putting the entire jq key reference in quote - but didnt work at all, may be i was doing something wrong with the subshell commands & jq (not a bash expert) value=$(echo $srcJson | jq ".root.parent.$srcKey" | sed -e 's/\\\"/\"/g' -e 's/^.//g' -e 's/.$//g')

  • 1
    There's existing Q&A telling you to use `jq --arg srcKey "$srcKey"` and to use `'.root.parent[$srcKey]'` inside the jq expression. – Charles Duffy Feb 27 '23 at 23:00
  • 1
    Also, `echo $srcJson | ...` is itself buggy. **Always** quote your expansions: `echo "$srcJson" | ...` -- see [I just assigned a variable, but `echo $variable` shows something else!](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else) – Charles Duffy Feb 27 '23 at 23:01
  • (the `$srcKey` in the jq expression above is correctly in single quotes because to do this correctly, we have the shell perform a replacement only in the `--arg` string; later, when we use `$srcKey` we're using it as a jq variable, not a shell variable; this prevents content within it from being parsed as jq syntax -- which is not just good practice but also a security measure) – Charles Duffy Feb 27 '23 at 23:03
  • BTW, as for why `.root.parent."$srcKey"` didn't work -- when you did it there in an unquoted context the quotes became shell syntax, whereas you need them to be jq syntax. – Charles Duffy Feb 27 '23 at 23:05

0 Answers0