0

Im executing a 'curl' operation and keeping the JSON response on a variable. Because I need to extract multiple values from this response I want to pass the variable to jq command instead of the curl operation (avoid multiple requests).

What I have tried so far:

JSON=$(curl ${URL})
#Test1
PARAM=$(JSON | jq -r '.param_one.val')
#Test2
PARAM=$( echo jq -r '.param_one.val' << "${JSON}" ) 
echo $PARAM #display result

How can I achieve this simple task?

Bugdr0id
  • 2,962
  • 6
  • 35
  • 59
  • 1
    `<<<"$JSON"`, not `<<"$JSON"`. And take out the `echo`. – Charles Duffy May 24 '19 at 15:26
  • 1
    (Also, don't use all-caps names for your own variables; those are reserved for names meaningful to the shell itself -- see POSIX spec @ https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html, fourth paragraph, keeping in mind that shell and environment variables share a single namespace). – Charles Duffy May 24 '19 at 15:26
  • Either use `echo "$JSON" | jq ...` or `jq ... <<<"$JSON"` (preferrably the second one). Your first try is incorrect because `JSON` isn't a command (`echo $JSON` instead would work), the second is incorrect because there shouldn't be an echo in front of `jq` and there's a missing `<` for the herestring – Aaron May 24 '19 at 15:28
  • 1
    Also, `echo "$PARAM"`, not `echo $PARAM`; see [BashPitfalls #14](http://mywiki.wooledge.org/BashPitfalls#echo_.24foo) and/or [SC2086](https://github.com/koalaman/shellcheck/wiki/SC2086) – Charles Duffy May 24 '19 at 15:28
  • 1
    You can usually extract your values in a single jq command, use `@tsv` to get them tab separated and then read them into an array: `IFS=$'\t' read -ra vals <<< "$(jq '[...] | @tsv')"` – Benjamin W. May 24 '19 at 15:29

0 Answers0