Home > other >  bash parse json and result with filter
bash parse json and result with filter

Time:08-18

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?

CodePudding user response:

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

CodePudding user response:

with jq in 1 line:

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

CodePudding user response:

Ed can do this.

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

ed -s file < edfind
  •  Tags:  
  • bash
  • Related