Home > Software engineering >  Fetch json data using Regex on linux
Fetch json data using Regex on linux

Time:11-03

I know we should use JQ for parsing json data, but I want to parse it using regex. I want to fetch the value of a json key into a variable in my shell script. As of now, I am using JQ for parsing.

So my abc.json is

{"value1":5.0,"value2":2.5,"value3":"2019-10-24T15:26:00.000Z","modifier":[],"value4":{"value41":{"value411":5}}}

Currently, my XYZ.sh has these lines to fetch the data

data1 =$(cat abc.json | jq -r '.value4.value41.value411')

I want data1 to have value 5. How can I achieve this?

CodePudding user response:

Is your json structure immutable? If you have to use it, consider the following

┌──[[email protected]]-[~]
└─$cat abc.json  | awk -F: '{print $NF}' | grep -o '[[:digit:]]'
5

CodePudding user response:

I think your problem was you had a space between data and =. There can't be a space there.

This works as you want it to (I removed the unnecessary cat)

data1=$(jq -r '.value4.value41.value411' abc.json)
echo $data1
  • Related