0

a curl command gives me a JSON output as follows:- [{"Description":"","Value":"bc","Key":"a"},{"Description":"","Value":"ef","Key":"d"},...]

Now I want to capture the values of only "Key" & "Value" in such a way that it if I perform echo $a it gives "bc", echo $d it gives "ef" etc.

Note: I am absolutely new in shell scripting/bash, thus this question

Thank you in advance

BlackPearl
  • 1,662
  • 1
  • 8
  • 16
Sourav Das
  • 51
  • 7

2 Answers2

1

You can use jq to parse the array and obtain the necessary value.

echo '[{"Description":"","Value":"bc","Key":"a"},{"Description":"","Value":"ef","Key":"d"}]' | jq '.[] | select(.Key == "d").Value'

This Should give you "ef" and,

echo '[{"Description":"","Value":"bc","Key":"a"},{"Description":"","Value":"ef","Key":"d"}]' | jq '.[] | select(.Key == "a").Value'

Will give you "bc"

You can replace the echo with your curl statement.

More about jq : https://stedolan.github.io/jq/

BlackPearl
  • 1,662
  • 1
  • 8
  • 16
  • On top of this answer (which I upvoted), if you actually expect values without quotes, add the `-r` flag when invoking `jq` – Httqm May 15 '19 at 09:44
  • @BlackPearl Thank you for the help. But for security reasons I am not able to install 'jq' here in my system. Also the output of the curl command may change, so I won't be sure about the keys or values..So need to write it and map it in such a way that if I perform echo $a it will give "bc", echo $d it will give "ef" and so on! – Sourav Das May 15 '19 at 10:03
0

Something like this may do the job :

dataString='[{"Description":"","Value":"bc","Key":"a"},{"Description":"","Value":"ef","Key":"d"},...]'
while read value key; do
    echo "key: '$key', value : '$value'"
done < <(echo "$dataString" | sed 's/},{/\n/g' | tr -d '[]{}"' | tr ':' ',' | cut -d',' -f 4,6 --output-delimiter=' ')

Details :

  • dataString is the output of curl
  • the whole (echo "$dataString"....) simply turns $dataString into :

    bc a

    ef d

  • the <(...) construct is a process substitution . It allows reading the output of a command with the same method you'd be reading from a file

Httqm
  • 799
  • 7
  • 13