How to parse JSON by command Line in Linux

13 / Dec / 2013 by arshad 2 comments

Java development is often challenging, especially when you need to parse JSON from the command line. In my recent Java development project I had parse JSON from the command line and I explored available options one-by-one to find a close fit solution which can be implemented quickly. 

Requirements

To parse json from the command line you’ll need a software called jq which is a command line JSON processor.

Installation

Step1: Download jq Binary

For 64-bit linux OS:  wget http://stedolan.github.io/jq/download/linux64/jq

For 32-bit linux OS : wget http://stedolan.github.io/jq/download/linux32/jq

Step 2: chmod +x ./jq

Step 3: sudo cp jq /usr/bin

In this blog, I will explain things with the help of Demo.json or demo.txt

{
  "OwnerId": "xyz",
  "ReservationId": "abc",
  "Groups": [],
  "State": {
      "Code": 0,
      "Name": "pending"
    },
  "Instances": [
  {
    "Monitoring": {
     "State": "disabled"
    },
    "SecurityGroups": [
    {
      "GroupName": "default",
      "GroupId": "sg-xxxx"
    }
    ],
    "NetworkInterfaces": [
     {
        "PrivateIpAddresses": [
        {
           "PrivateDnsName": "ip-xx-xx-yy-yyy",
           "Primary": true,
           "PrivateIpAddress": "xx.xx.yy.yyy"
        }
        ],
        "PrivateDnsName": "ip-xxx-xx-yy-yyy"
       }
     ]
   }
 ]
}

Some of the frequently used use-cases have been discussed below with Command and their respective output:

1 : To parse a JSON object:

Command :

cat Demo.json | jq '.OwnerId'

Output :

"xyz"

2: To parse a nested JSON object:

Command :

cat Demo.json | jq '.State.Name'

Output :

"pending"

3: To extract specific fields from a JSON object:

Command :

cat Demo.json | jq '.State | { Code , Name}'

Output :

{
"Name": "pending",
"Code": 0
}

4: To parse a JSON array:

Command :

cat Demo.json | jq '.Instances[0].Monitoring'

Output :

{
"State": "disabled"
}

Command :

cat Demo.json | jq '.Instances[0].Monitoring.State'

Output :

"disabled"

Command :

cat Demo.json | jq '.Instances[0].NetworkInterfaces[0].PrivateIpAddresses[0].PrivateDnsName'

Output :

"ip-xxx-xx-yy-yyy"

In cases where you only need the value; you have to remove the “” by using pipeline in linux

Command :

cat Demo.json | jq '.OwnerId' | cut -d "\"" -f 2

Output :

xyz

Hope you will be able to parse JSON by command line for your next project.

FOUND THIS USEFUL? SHARE IT

comments (2)

Leave a comment -