Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract values from a Json in bash [duplicate]

I am trying my hand on shell scripting and was trying to extract values from a Json and store it into a variable to use it later. But I am unable to do so, have tried follow up lots of links and suggestion, probably I am doing something wrong. Basically I am using curl to hit an url and from the response I am trying to extract the value of a status field . I am trying the following lines,

result=$(curl "http://localhost:9200/domains" | grep "status" | awk '{print $1 }') echo "the result is" $result

The curl command will fetch something like

{"error":{"root_cause":[{"type":"index_not_found_exception","reason":"no such index","resource.type":"index_or_alias","resource.id":"domains","index_uuid":"_na_","index":"domains"}],"type":"index_not_found_exception","reason":"no such index","resource.type":"index_or_alias","resource.id":"domains","index_uuid":"_na_","index":"domains"},"status":404}

Any help in this regard is really appreciated. I know we can do it in jq or perl but I am looking for a solution using grep, sed or awk.

Thanks Ashit

like image 477
Ashit_Kumar Avatar asked Mar 20 '26 21:03

Ashit_Kumar


1 Answers

Using grep and awk

result=$(curl "http://localhost:9200/domains" | \
    grep -o -E "\"status\":[0-9]+" | awk -F\: '{print $2}')
  1. First, use grep to extract the pattern status:[0-9]+
  2. Then, use awk to split the result by : and print the second field
like image 72
Lee HoYo Avatar answered Mar 23 '26 21:03

Lee HoYo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!