Thursday 13 May 2021

jq: functions

jq command line tool several functions that are used while processing json data.

 

Example

keys: Return all the keys of json document

length: Return length. Output of ‘length’ function depends on the input.

a.   If a string is passed, then it returns the number of characters in the string

b.   If an array is passed, then it return the number of elements in the array

c.    If an object is passed, then it return the number of key-value pairs.

 

empPretty.json 

{
	"org": [{
		"name": "Honeywell",
		"yrsOfExperience": 2.2
	}, {
		"name": "IBM",
		"yrsOfExperience": 1.8
	}],
	"firstName": "Krishna",
	"lastName": "Ram",
	"address": {
		"city": "Bangalore",
		"country": "India"
	}
}

 

Get all the keys of json document

$cat empPretty.json | jq 'keys'
[
  "address",
  "firstName",
  "lastName",
  "org"
]

 

Get all the key of ‘org’ property

$cat empPretty.json | jq '.org[0] | keys'
[
  "name",
  "yrsOfExperience"
]

 

Get number of elements in the org array

$cat empPretty.json | jq '.org | length'
2

Get length of city property

$cat empPretty.json | jq '.address.city | length'
9
$
$cat empPretty.json | jq '.address | .city | length'
9



 

 

 

 

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment