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
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
[js]
{
"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"
}
]
}
]
}
[/js]
Some of the frequently used use-cases have been discussed below with Command and their respective output:
1 : To parse a JSON object:
Command :
[js]cat Demo.json | jq ‘.OwnerId'[/js]
Output :
[js]"xyz"[/js]
2: To parse a nested JSON object:
Command :
[js]cat Demo.json | jq ‘.State.Name'[/js]
Output :
[js]"pending"[/js]
3: To extract specific fields from a JSON object:
Command :
[js]cat Demo.json | jq ‘.State | { Code , Name}'[/js]
Output :
[js]{
"Name": "pending",
"Code": 0
}[/js]
4: To parse a JSON array:
Command :
[js]cat Demo.json | jq ‘.Instances[0].Monitoring'[/js]
Output :
[js]{
"State": "disabled"
}[/js]
Command :
[js]cat Demo.json | jq ‘.Instances[0].Monitoring.State'[/js]
Output :
[js]"disabled"[/js]
Command :
[js]cat Demo.json | jq ‘.Instances[0].NetworkInterfaces[0].PrivateIpAddresses[0].PrivateDnsName'[/js]
Output :
[js]"ip-xxx-xx-yy-yyy"[/js]
In cases where you only need the value; you have to remove the “” by using pipeline in linux
Command :
[js]cat Demo.json | jq ‘.OwnerId’ | cut -d "\"" -f 2[/js]
Output :
[js]xyz[/js]
Hope you will be able to parse JSON by command line for your next project.
thank you very much. It’s help me lot !