Tuesday, December 9, 2014

How to extract a JSON value from a BASH script



Requirement : I was working on shell script where I need to get Id value from JSON and I tried so many thing but unable to get it without using any other tools. So, After trying so many failure attempt, I end up with this site (A big thanks to you) which resolved my issue.


Here is how I fetched value from JSON,


JSON = <YOUR_JSON>
PROPERTY_TO_FETCH="<VALUE>" (In my case, it was "id")

ID = `echo $JSON| sed 's/\\\\\//\//g' | sed 's/[{}]//g' | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' | sed 's/\"\:\"/\|/g' | sed 's/[\,]/ /g' | sed 's/\"//g' | grep -w $PROPERTY_TO_FETCH`

echo ${ID ##*|}


Which will print the value of 'id' from JSON.

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...