0

I have the following json:

{
    "feature/EBS_DDS_SC-27428": {
        "auth": "http://test123:8080/service.jsp",
        "publish": "http://test234:8080/service.jsp",
        "general_name": "PG"
    },
    "feature/EBS_DDS_SC-27428": {
        "auth": "http://ab123:8080/service.jsp",
        "publish": "http://ab234:8080/service.jsp",
        "general_name": "PG1"
    }

}

when I do the following I get the expected result

jq --raw-output '."feature/EBS_DDS_SC-27428" | .auth'

But the following is not working,

export branch=feature/EBS_DDS_SC-27428
cat input.json | jq --raw-output '."${branch}" | .auth'

I get the following compilation error:

jq: error: syntax error, unexpected '$' (Unix shell quoting issues?) at <top-level>, line 1:
.${branch} | .auth
jq: error: try .["field"] instead of .field for unusually named fields at <top-level>, line 1:
.${branch} | .auth
jq: 2 compile errors

Now I have an environmental variable called branch in my Linux machine

  • Does this answer your question? [Passing bash variable to jq select](https://stackoverflow.com/questions/40027395/passing-bash-variable-to-jq-select) – oguz ismail Dec 03 '19 at 17:48

2 Answers2

1

In your specific case I think you have a small bash quoting error causing ${branch} to be treated as a constant. I think you want to quote it like this:

     '."'      "${branch}"         '" | .auth'
     ------    ------------------  -----------
     single    double quote so     single
     quote     shell expands the   quote
     constant  branch variable     constant

Sample Run

$ echo '."'"${branch}"'" | .auth'
."feature/EBS_DDS_SC-27428" | .auth

$ cat input.json | jq --raw-output '."'"${branch}"'" | .auth'
http://ab123:8080/service.jsp

The variable substitution section of the Advanced Bash Scripting Guide is your friend.

jq170727
  • 13,159
  • 3
  • 46
  • 56
0

I have an environmental variable called branch

Environment variables (as opposed to shell variables) can be dereferenced in jq programs using the env object. In your case, you'd write env.branch.

If you wanted to make the value of a variable accessible as $branch in the shell, it is best to use the --arg command-line option, along the lines of:

jq --arg branch "$branch"

That way, you can reference the value as $branch in the jq program. In the specific case of the Q, you could (for example) write:

jq -r '.[$branch].auth'
peak
  • 105,803
  • 17
  • 152
  • 177