AlexC AlexC - 7 months ago 50
Bash Question

A better way to extract JSON value in bash script

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


is stored in myFile.txt and I just want the KeyValue (without quotes). What I've currently got is :

IFS=': ' read -a arr <<< $PAIR
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.



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:

[[ $PAIR =~ ^\{\"([^\"]+)\":\"([^\"]+)\"\}$ ]] && echo "The key is ${BASH_REMATCH[1]} and the value is ${BASH_REMATCH[2]}"

[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 of php -r "print_r( json_decode('"$PAIR"') );" for instance...]