'How to extract value from json contained in a variable using jq in bash

I am writing a bash script which has a json value stored in a variable now i want to extract the values in that json using Jq. The code used is.

json_val={"code":"lyz1To6ZTWClDHSiaeXyxg","redirect_to":"http://example.com/client-redirect-uri?code=lyz1To6ZTWClDHSiaeXyxg"}
  code_val= echo"$json_val" | jq '.code'

This throws an error of no such file or direcotry.

If i change this to

json_val={"code":"lyz1To6ZTWClDHSiaeXyxg","redirect_to":"http://example.com/client-redirect-uri?code=lyz1To6ZTWClDHSiaeXyxg"}
  code_val=echo" $json_val " | jq '.code'

This does not throws any error but the value in code_val is null.

If try to do it manually echo {"code":"lyz1To6ZTWClDHSiaeXyxg","redirect_to":"http://example.com/client-redirect-uri?code=lyz1To6ZTWClDHSiaeXyxg"} | jq '.code' it throws parse numeric letter error.

how can i do it in first case.



Solution 1:[1]

You may use this:

json_val='{"code":"lyz1To6ZTWClDHSiaeXyxg","redirect_to":"http://example.com/client-redirect-uri?code=lyz1To6ZTWClDHSiaeXyxg"}'
code_val=$(jq -r '.code' <<< "$json_val")
echo "$code_val"

lyz1To6ZTWClDHSiaeXyxg

Note following changes:

  • Wrap complete json string in single quotes
  • use of $(...) for command substitution
  • Use of <<< (here-string) to avoid a sub-shell creation

PS: If you're getting json text from a curl command and want to store multiple fields in shell variables then use:

read -r code_val redirect_to < <(curl ... | jq -r '.code + "\t" + .redirect_to')

Where ... is your curl command.

Solution 2:[2]

If try to do it manually:

$ echo {"code":"lyz1To6ZTWClDHSiaeXyxg","redirect_to":"http://example.com/client-redirect-uri?code=lyz1To6ZTWClDHSiaeXyxg"} | jq '.code'

...it throws parse numeric letter error.

seems like you did not escape the string of the echo command. in your case, escaping with a singe-quote (apostrophe ') will do - same as you did with the jq json-path argument ('.code')

$ echo '{"code":"lyz1To6ZTWClDHSiaeXyxg","redirect_to":"http://example.com/client-redirect-uri?code=lyz1To6ZTWClDHSiaeXyxg"}' | jq '.code'
"lyz1To6ZTWClDHSiaeXyxg"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 bloodyKnuckles