Friday, 15 January 2021

JQ saves me time AND typing

 Over the past few months, I've been getting more to grips with jq and have only just realised that I can actually use it to parse JSON way better than using grep and awk and sed.

TL;DR; I've got a Bash script that generates an Access Token by wrapping a cURL command e.g.

export ACCESS_TOKEN=$(curl -s -k -X POST -H 'Content-Type: application/json' -d '{"kind": "request","parameters":{"user": "blockchain","password": "passw0rd"}}')

I was previously using a whole slew of commands to extract the required token from the response: -

{ "kind": "response", "parameters": { "token": "this_is_a_token", "isAdmin": true } }

including json_pp and grep and awk and sed e.g.

export ACCESS_TOKEN=$(curl -s -k -X POST -H 'Content-Type: application/json' -d '{"kind": "request","parameters":{"user": "user","password": "passw0rd"}}' | json_pp | grep -i token | awk '{print $3}' | sed -e 's/"//g' | sed -e 's/,//g')

And then I realised ... this is JSON, right ?

So why am I using conventional Unix scripting tools to munge JSON ?

So I stripped 'em all out and ended up with this: -

export ACCESS_TOKEN=$(curl -s -k -X POST -H 'Content-Type: application/json' -d '{"kind": "request","parameters":{"user": "user","password": "passw0rd"}}' | jq -r .parameters.token)

In other words, I replaced json_pp with jq and used that to parse the response for the .token element of the .parameters object ...

Note that I'm using jq -r ( aka raw ) to remove the double quotes ( " ) around the token element of the response.

Way simpler ! Now off to wrangle the rest of my scripts ...


No comments:

Today I Learned - more about Git config

Whilst trying to create a container image from a project on GitHub, I hit an issue with the cloning process of the GH repository ... Specifi...