Quick actions

cmd+k|ctrl+k

Navigation

Languages

Play with JQ

Snippet info

Language

Bash

Visibility

public

Author

gurutech

Created

2017-12-30T19:47:50Z

Updated

2017-12-30T19:59:16Z

#!/bin/bash

# Visit and share my telegram channel with your friends: http://t.me/linuxcheatsheet

# Run this code on your local computer: you can't use external tools like jq on glot.io
# And don't forget to install jq to use this script!
# yum install jq or apt-get install jq or pacman -S jq or whatever your distro use for packages!

# The json example was taken from:
# https://github.com/LearnWebCode/json-example/blob/master/animals-1.json

# For the purpose of this exercise, I will generate a sample json on the fly
# and save it to a tmpfile.


which jq 2> /dev/null &> /dev/null
if ( [ $? -ne 0 ] ); then echo "You must install jq to use the script!"; exit 0; fi

TMPJSON=$(mktemp)

cat << EOF > $TMPJSON
[
  {
    "name": "Meowsy",
    "species" : "cat",
    "foods": {
      "likes": ["tuna", "catnip"],
      "dislikes": ["ham", "zucchini"]
    }
  },
  {
    "name": "Barky",
    "species" : "dog",
    "foods": {
      "likes": ["bones", "carrots"],
      "dislikes": ["tuna"]
    }
  },
  {
    "name": "Purrpaws",
    "species" : "cat",
    "foods": {
      "likes": ["mice"],
      "dislikes": ["cookies"]
    }
  }
]
EOF

# First filter you need to know: the 'dot' filter. It does nothing to your json but output it again

echo "Using dot filter"
sleep 2
jq . $TMPJSON
echo "Press any key to continue..."
read -sN1

echo "You can use dot filter to check if a json if valid"
jq . $TMPJSON 2> /dev/null &> /dev/null
if ( [ $? -eq 0 ] ); then echo "*** Valid json [OK]"; else echo "*** Broken Json [ERROR]"; fi
echo "Press any key to continue..."
read -sN1

echo "Let's skip a line in our example json to break it on purpose"
tail +2 $TMPJSON | jq . 2> /dev/null &> /dev/null
if ( [ $? -eq 0 ] ); then echo "*** Valid json [OK]"; else echo "*** Broken Json [ERROR]"; fi
echo "Press any key to continue..."
read -sN1

# .[] extract all elements in the json array between [ and  ]
# then I combine (pipe sign) it with the "select" filter.
# I will select all the objects where the json key named species equals cat

echo "I love cats ;-) let's select its from our json"
jq '.[] | select(.species == "cat")' $TMPJSON
echo "Press any key to continue..."
read -sN1

# You can of course combine multiple filters.
# Depending on the structure of the json, you can extract some keys
# like the names of all cats in the example

echo "What are its names?"
jq '.[] | select(.species == "cat") | .name' $TMPJSON

echo "That's all for this small example!"
echo "I hope you found this useful! Visit and share my telegram channel with your friends: http://t.me/linuxcheatsheet"
[ -f $TMPJSON ] && rm -f $TMPJSON

exit 0
INFO