Home > Mobile >  How to escape a double quotation marks AND using a env var in JQ
How to escape a double quotation marks AND using a env var in JQ

Time:06-01

I have the following file: data.txt

{
  "1": {
    "job": "Plumber",
    "age": "23"
  },
  "2": {
    "job": "SEO",
    "age": "45"
  }
}

And I can do the following query without problem:

jq --raw-output '."2".job' data.txt

But, in the script that I am doing, the number is given from another command, something similar to this next for simplicity. And at the time of executing it, it does not parse the variable or the quotes well. So the result be null.

ID=$(echo "2")
jq --raw-output '."$ID".job' README.md

I've tried escaping the variable with \, escaping the quotes with \, escaping both with \. Also to use --arg and .["$env.ID"] and everything that come to my head. Unsuccessfully. If anyone knows how to parse quotes and a variable at same time I would be very grateful, regards.

CodePudding user response:

You are trying to construct a JQ filter using string interpretation, which is typically the wrong thing to do.

Instead, pass the number as an argument to the filter.

ID=2
jq --raw-output --arg x "$ID"  '.[$x].job' data.txt
# jq --raw-output --argjson x "\"$ID\"" '.[$x].job' data.txt

# ID='"2"'
# jq --raw-output --argjson x "$ID" '.[$x].job' data.txt

--arg encodes the value as a JSON string; --argjson assumes that the value is already a JSON value.

  • Related