A better way to extract JSON value in bash script

2019-03-07 07:13发布

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 shell
2条回答
冷血范
2楼-- · 2019-03-07 07:46

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='{"myKeyName":"myKeyValueVariableLength"}'
[[ $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...]

查看更多
对你真心纯属浪费
3楼-- · 2019-03-07 08:00

jq is designed for processing JSON:

jq -r '.myKeyName' myFile.txt
查看更多
登录 后发表回答