Can anyone suggest a better / neater way to extract the value from a Json pair than what I've got so far below pls...
My Json pair is
{"myKeyName":"myKeyValueVariableLength"}
is stored in myFile.txt and I just want the KeyValue (without quotes). What I've currently got is :
#!/bin/bash
PAIR=$(<myFile.txt)
IFS=': ' read -a arr <<< $PAIR
ONE="${arr[1]%?}"
TWO="${ONE%?}"
THREE=${TWO#'"'}
echo $THREE
This does work for me but I'm guessing there is a much neater way ? I have heard of jsawk but would like to try and do all within bash if possible.
Tks
Bash contains a built-in regex test, which takes the form
[[ string =~ regex ]]
. After it's run, captured sub-patterns are stored in an array called$BASH_REMATCH
It's a bit fussy / magic about handling quotes and escapes, so it took me a while to get working, but this seems to work:
[Alternatively, do it The Unix Way, and invoke
sed
,awk
,perl
,python
,php
, or whatever you have installed that will make your life easier. Something along the lines ofphp -r "print_r( json_decode('"$PAIR"') );"
for instance...]jq
is designed for processing JSON: