Wednesday, 20 March 2019

JSON parsing with conditional filter with jq + shell


JSON parsing with conditional filter


For e.g. We have a json as below. We want to get the "format" field value when name is "Test".

{
  "name": "maven-snapshots",
  "format": "maven2",
  "type": "proxy",
  "url": "http://<host>:<port>/repository/maven-snapshots"
}
{
  "name": "Test",
  "format": "yum",
  "type": "hosted",
  "url": "http://<host>:<port>/repository/Test"
}
{
  "name": "Test_Group",
  "format": "maven2",
  "type": "group",
  "url": "http://<host>:<port>/repository/Test_Group"
}


We can get  it by:      jq -r '.[] | select(.name=="Test") | .format' 
 This will filter the "name" field and if it matches then return the "format" field value for that array element.

We can parse this from URL by below command.

curl -s -u admin:admin123 -X GET 'http://<host>:<port>/service/rest/v1/repositories' | jq -r '.[] | select(.name=="Test")|.format'


To get the number of elements in JSON array

 jq length 

To get the type of object 

jq type 

To get values with comma separated in same line 


jq  -r '.[] | [.date, .count, .word] | @csv'
"2011-01-12 13:14",17,"This"
"2011-01-13 21:30",4711,"That"

No comments:

Post a Comment

Thank You for your valuable comment

Difference between class level and object locking and static object lock

1) Class level locking will lock entire class, so no other thread can access any of other synchronized blocks. 2) Object locking will lo...