0

I tried using Parse JSON to array in a shell script

but unable to get required field. Below is my json:

{
    "status": "UP",
    "databaseHealthCheck": 
    {
        "status": "UP",
        "dataSource": 
        {
            "maxActive": 100,
            "maxIdle": 8,
            "numActive": 0,
            "url": "jdbc:oracle:thin:@hostname:port/db_name",
            "userName": "test_123"
        }
    },

    "JMSHealthCheck": 
    {
        "status": "UP",
        "producerTemplate": 
        {
            "name": "Test_2",
            "pendingCount": 0,
            "operator": "<"
        }
    },

    "diskSpace": 
    {
        "status": "UP",
        "total": 414302519296,
        "free": 16099868672,
        "threshold": 10485760
    }
}

I want to extract pendingCount value under producerTemplate under JMSHealthCheck.

Have restriction to use utility like jq.

Bash Version 3.x

1
  • You should hire a programmer. Seriously, you haven't even shown any effort to solve your homework problem yourself. Read How to Ask and provide a minimal reproducible example. Commented May 30, 2018 at 6:06

1 Answer 1

1

In absence of jq, you may use this gnu grep command:

read -r s < <(grep -zoP '"JMSHealthCheck":\s*{[^{}]*?"producerTemplate":\s*{[^{}]*?"pendingCount":\h*\K\d+' file.json)

echo "$s"

0

However, please keep in mind that parsing a JSON using regex is not recommended. If you have jq then it would be a very simple jq command lke this:

jq '.JMSHealthCheck.producerTemplate.pendingCount' file.json
Sign up to request clarification or add additional context in comments.

4 Comments

json_parsing.sh: line 17: syntax error near unexpected token <' json_parsing.sh: line 17: read -r s < <(grep -zoP '"JMSHealthCheck":\s*{[^{}]*?"producerTemplate":\s*{[^{}]*?"pendingCount":\h*\K\d+' myfile.json)'
First check output of grep -zoP '"JMSHealthCheck":\s*{[^{}]*?"producerTemplate":\s*{[^{}]*?"pendingCount":\h*\K\d+' myfile.json. Error you are getting is because you're not using bash
grep: The -P and -z options cannot be combined using bash already
See this working demo with same command. Check your grep version. As I mentioned it requires gnu grep

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.