bash parse json and result with filter

I have the following json saved in the variable called $result

{
   "count":3,
   "value":[
      {
         "id":11,
         "name":"John"
      },
      {
         "id":22,
         "name":"Terry"
      },
      {
         "id":33,
         "name":"Stacey"
      }
   ]
}

how can I get the id of Terry using some sort of filter like name == Terry? preferably using grep command?

Upvotes: 0

Views: 70

Answers (3)

petrus4
petrus4

Reputation: 614

Ed can do this.

cat << EOF >> edfind
/Terry/
-1p
EOF

ed -s file < edfind

Upvotes: 0

xvdd
xvdd

Reputation: 21

with jq in 1 line:

$ echo $RESULT | jq '.value[] | select(.name | contains("Terry")) | .id'
22

Upvotes: 2

Tathastu Pandya
Tathastu Pandya

Reputation: 326

grep_id() { cat $1 | grep "$2" -B1 | grep -o "[0-9]+" -E; }

Usage:

grep_id filename name_value
grep_id filemame Terry 
22
grep_id filename John
11

Another based on awk

grep_awk() { awk -v var=$2 '$0 ~ var {if (a && a !~ /foo/); gsub(/[^[:digit:]]/, "", a); print a} {a=$0}' $1; }
Usage:
grep_awk filename John
11

Another based in jq

jq_id() { jq --arg name $2 '.value[] | select( .name == $name ).id' $1; }
Usage:
jq_id filname name_value
jq_id filename Stacey
33

Upvotes: 4

Related Questions