tata
tata

Reputation: 33

Parse JSON response using shell script

{
    "PlatformID": 1024,
    "SystemId": 11640,
    "SystemName": "010.10.10.10",
    "DomainName": null,
    "AccountId": 15631,
    "AccountName": "merg1",
    "AccountNameFull": "merg1",
    "ApplicationID": null,
    "ApplicationDisplayName": null,
    "MaximumReleaseDuration": 120,
    "MaxReleaseDurationDays": 0,
    "MaxReleaseDurationHours": 2,
    "MaxReleaseDurationMinutes": 0,
    "InstanceName": "",
    "DefaultReleaseDuration": 120,
    "DefaultReleaseDurationDays": 0,
    "DefaultReleaseDurationHours": 2,
    "DefaultReleaseDurationMinutes": 0,
    "LastChangeDate": "2019-08-21T10:53:25.237",
    "NextChangeDate": null,
    "IsChanging": false,
    "IsISAAccess": false,
    "PreferredNodeID": "3ef3e7c7-5851-451b-b1a4-c62556b588ce"
}

I am looking for "SystemId and AccountId" from the above JSON response without using jq tool.

Kindly help with the shell script. Thank you.

Upvotes: 0

Views: 673

Answers (3)

tata
tata

Reputation: 33

sysID=$(echo $JSON | tr , '\n' | grep SystemId | awk -F ':' '{print $2}')
accID=$(echo $JSON | tr , '\n' | grep AccountId | awk -F ':' '{print $2}')

echo "System ID = $sysID, Account ID = $accID"

This worked for me...! without using jq tool

Upvotes: 0

9mat
9mat

Reputation: 1234

If you are sure of the structure of the json file, and the following steps should work (this requires that a pair key and value is always on the same line -- if not we need to remove any white space before and after the colon)

  1. separate each field to a separate line
  2. use grep to extract the line that has SystemId or AccountId
  3. use awk to extract the second field in that line (delimited by the colon)
cat a.json | tr , '\n' | grep SystemId | awk -F ':' '{print $2}'
11640

cat a.json | tr , '\n' | grep AccountId | awk -F ':' '{print $2}'
15631

Edited: if json is in a varaible, and there is a need to save the output to variable:

#!/bin/bash

JSON=$(cat a.json)


sysID=$(echo $JSON | tr , '\n' | grep SystemId | awk -F ':' '{print $2}')
accID=$(echo $JSON | tr , '\n' | grep AccountId | awk -F ':' '{print $2}')

echo "System ID = $sysID, Account ID = $accID"

# output
# System ID =  11640, Account ID =  15631

Upvotes: 0

Adem Öztaş
Adem Öztaş

Reputation: 21446

You can use grep on the following usage.

grep -E -- 'AccountId|SystemId' t.txt | awk '{print $2}'
11640,
15631,

Or If would you like to use jq you can try this one.

cat t.txt | jq '.AccountId , .SystemId'
15631
11640

Upvotes: 1

Related Questions