Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

shell

jq

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.

like image 937
Rahul Avatar asked Jan 01 '20 10:01

Rahul


People also ask

What does jq do in bash?

jq command is used not only for reading JSON data but also to display data by removing the particular key. The following command will print all key values of Students. json file by excluding batch key. map and del function are used in jq command to do the task.

Does jq use JSONPath?

jp is a JSON processor for the command line using JSONPath (aka "a simpler jq, and with JSONPath").


1 Answers

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.

like image 62
anubhava Avatar answered Oct 08 '22 07:10

anubhava