Get json value using regex in linux

122 Views Asked by At

I have a json file file.json like this:

{
  "abc": "123",
  "def": 456,
  "ghi": 789
}

I am trying to get value of all the keys using regex in bash terminal.

Here is what I tried for getting value of abc:

var=cat file.json
regex='(abc\":) \"(.+)\",'
[[ $var =~ $regex ]]
echo ${BASE_REMATCH[1]}

It doesn't print anything. I am trying to get/print value of abc i.e. "123"

Please note that I can't use jq parser.

1

There are 1 best solutions below

0
Julio On

While it is generally advised to use a Json parser (don't badly do work that has already be well done by someone else) It is sometimes just OK to parse Json via regex for use-and-throw-away scripts, or for parsing very simple json files/strings (like the one you used in your input)

If that is your case, this may work for you (as long as the values are scalars)

var=$(cat file.json)
regex='"abc"[[:space:]]*:[[:space:]]*("([^"]+|\\")+"|[^[:space:],"]+)'

[[ $var =~ $regex ]]

if [[ $var =~ $regex ]]; then
  echo ${BASH_REMATCH[1]}
fi

For any other cases, use a json parser.

Perl is installed on almost every Linux flavour, and the module JSON::PP should be part of the core modules.

So you could do something like this:

perl -MJSON::PP -E '$j=decode_json <>; say $j->{abc}' -0777 file.json