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

virendrao
  • 1,763
  • 2
  • 22
  • 42
  • You should hire a programmer. Seriously, you haven't even shown any effort to solve your homework problem yourself. Read [ask] and provide a [mcve]. – Ulrich Eckhardt May 30 '18 at 06:06

1 Answers1

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 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)' – virendrao May 30 '18 at 06:43
  • 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` – anubhava May 30 '18 at 06:46
  • grep: The -P and -z options cannot be combined using bash already – virendrao May 30 '18 at 06:49
  • [See this working demo with same command](https://ideone.com/WhtmjU). Check your `grep` version. As I mentioned it requires `gnu grep` – anubhava May 30 '18 at 06:52