linus2303
linus2303

Reputation: 1

Parse json into array in bash

{
    "db_status": {
        "sysa": {
            "taskname": "AB",
            "state": "Running",
            "status": "System ATTENTION",
            "updated": "0727",
            "version": "5"
        },

        "sysb": {
            "taskname": "null",
            "state": "Standby",
            "status": "System OK",
            "updated": "0727",
            "version": "6"
        }
    }
}

CURL command returns json object. Trying to get both state variables in an array i.e. running and standby. So far i have tried

curl -s http://localhost:9099/api | grep state | sed 's/"//g' | awk -F  ": " '/state/ {print $2}' | tr '\n' ' ' |  sed s'/..$//'

Upvotes: 0

Views: 4534

Answers (2)

Ed Morton
Ed Morton

Reputation: 204721

FYI you don't need a pipeline of 20 different commands when you're using awk. The command line you provided can be written as just one command:

awk -F'"' '$2=="state"{printf "%s%s", (++c>1?", ":""),$4}'

but all you really need is:

awk -F'"' '$2=="state"{print $4}'

and to save the output in a shell array (assuming your json is really always formatted as you show in your question) would be:

$ arr=( $(cat file | awk -F'"' '$2=="state"{print $4}') )
$ echo "${arr[0]}"
Running
$ echo "${arr[1]}"
Standby

Replace cat file with your curl command.

Upvotes: 2

Soren
Soren

Reputation: 14718

You could use jq

$ curl -s http://localhost:9099/api | jq '.db_status.sysa.state, .db_status.sysb.state'
"Running"
"Standby"

Or if you want all the entries no matter how many

$ curl -s http://localhost:9099/api | jq '.db_status[].state'
"Running"
"Standby"

Alternatively, if you don't have jq (or just looking for ways of feeling pain) you can parse most json in bash using ticktick -- which is written in 250 lines of bash

Upvotes: 1

Related Questions