0

Here is the bash function to parse a json file use 'jq' command:

jq_fullpath_endkey() {
      PATHARRAY=$(jq -c 'paths | select(.[-1] == "'$keyword'")|map(strings |= ".\(.)" | numbers |= "[\(.)]") | join("")' **${news.json}**)
}

The news.json is the json file that contains all the content I'd like to parse with jq.

The function works once I replace ${news.json} with a variable named response which contains news.json content as string.

Below is the command which works:

  PATHARRAY=$(jq -c 'paths | select(.[-1] == "'$keyword'")|map(strings |= ".\(.)" | numbers |= "[\(.)]") | join("")'**<<< "$response"**)

My question is how can I use 'json file' as part of the jq cmd ? I suspect there is something wrong with double/single quote I am using.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jia
  • 2,417
  • 1
  • 15
  • 25
  • Are you passing the filename as a parameter to the function (i.e. `jq_fullpath_endkey news.json`)? If so, just use `"$1"` in the command. BTW, the way you're injecting `$keyword` is not recommended -- use `--arg` instead (see [this example](https://stackoverflow.com/questions/52959216/passing-bash-shell-variable-to-jq-filter)). – Gordon Davisson May 03 '22 at 02:39
  • yes, it works :) , I am using "parameter substitution" and it works also. thanks ! – Jia May 03 '22 at 03:11

1 Answers1

0

I figure it out with "parameter substitution" in bash

myfile="news.json"
PATHARRAY=$(jq -c 'paths | select(.[-1] == "'$keyword'")|map(strings |= ".\(.)" | numbers |= "[\(.)]") | join("")' ${myfile})

Related concepts: variable substitution command substitution

Jia
  • 2,417
  • 1
  • 15
  • 25