-1

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.

mmk
  • 480
  • 3
  • 10
  • 5
    Use proper tools to parse json, i.e. `jq` – Diego Torres Milano Jan 30 '23 at 07:52
  • @DiegoTorresMilano, I don't have jq available on linux machine where I am trying to use it. – mmk Jan 30 '23 at 07:52
  • 2
    One cannot put a screw with a hammer. If you cannot use jq to parse JSON within shell, then check other available languages with JSON parsing support. Python, PHP, Perl have it natively. And if none is available to you, then get the machine administrator to install the tool you need for the job you need to perform. If you are an employee, a contractor or a student, it is up to your employer, customer or school to provide you with the tools you need. – Léa Gris Jan 30 '23 at 08:27
  • The marked duplicate shows answer in jq, grep, jsawk, python, node, sed. Please find your personal favorite there. – 0stone0 Jan 30 '23 at 10:12

2 Answers2

0

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
Julio
  • 5,208
  • 1
  • 13
  • 42
-1

Reading your file.json from stdin with python 3.

example.py:

import sys
import json

f = open(sys.stdin.fileno(), 'r')
data = json.load(f)

print(data[sys.argv[1]])

Usage: python3 example.py 'abc' < file.json

Output:

123
Cyrus
  • 84,225
  • 14
  • 89
  • 153