Saturday, 15 May 2021

Jq: Complex queries example

 

emps.json

emps.json 
[{
		"id": 1,
		"firstName": "Ram",
		"lastName": "Gurram",
		"age": 23
	},
	{
		"id": 2,
		"firstName": "Sailaja",
		"lastName": "PTR",
		"age": 31
	},
	{
		"id": 3,
		"firstName": "Venkat",
		"lastName": "IT",
		"age": 30
	},
	{
		"id": 4,
		"firstName": "Gopi",
		"lastName": "Battu",
		"age": 34
	}
]

 

a. Get all the employees whose firstName contains string ‘a’

$cat emps.json | jq '.[] | select((.firstName | contains("a")))'
{
  "id": 1,
  "firstName": "Ram",
  "lastName": "Gurram",
  "age": 23
}
{
  "id": 2,
  "firstName": "Sailaja",
  "lastName": "PTR",
  "age": 31
}
{
  "id": 3,
  "firstName": "Venkat",
  "lastName": "IT",
  "age": 30
}

 

b. Get all the employees whose firstName contains string ‘ai’

$cat emps.json | jq '.[] | select((.firstName | contains("ai")))'
{
  "id": 2,
  "firstName": "Sailaja",
  "lastName": "PTR",
  "age": 31
}

 

c. Get all the ids of employees whose name contains string ‘ai’

$cat emps.json | jq '.[] | select((.firstName | contains("ai"))) | .id'
2

 

d. Get all the employees firstName and lastName whose id is even number

$cat emps.json | jq '.[] | select((.id % 2 == 0)) | .firstName+","+.lastName+"," +(.id|tostring)'
"Sailaja,PTR,2"
"Gopi,Battu,4"


e. Get all the employees firstName and lastName whose id is odd number

$cat emps.json | jq '.[] | select((.id % 2 != 0)) | .firstName+","+.lastName+"," +(.id|tostring)'
"Ram,Gurram,1"
"Venkat,IT,3"

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment