Difference between revisions of "Jq"
From Christoph's Personal Wiki
(Created page with "'''jq''' is a lightweight and flexible command-line JSON processor. jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data...") |
|||
Line 82: | Line 82: | ||
$ foo=($(cat azones3.json | jq -cM '[.availabilityZoneInfo[] | select(.zoneName == "az1") | {hosts: .hosts|keys}]' | sed -e 's/["}\[]//g;s/\]//g;s/{hosts://g;s/,/ /g')) | $ foo=($(cat azones3.json | jq -cM '[.availabilityZoneInfo[] | select(.zoneName == "az1") | {hosts: .hosts|keys}]' | sed -e 's/["}\[]//g;s/\]//g;s/{hosts://g;s/,/ /g')) | ||
$ echo ${foo[0]} #=> node-1.example.com | $ echo ${foo[0]} #=> node-1.example.com | ||
+ | |||
+ | * Get just the raw values: | ||
+ | |||
+ | $ echo '{ "packet_loss": [ {"ips": "10.0.0.10 10.0.0.11 10.0.0.12", "node-17": "3/3" }] }' | jq -r '[.packet_loss[] | .ips] | .[]' | ||
+ | 10.0.0.10 10.0.0.11 10.0.0.12 | ||
==External links== | ==External links== |
Revision as of 23:46, 11 February 2016
jq is a lightweight and flexible command-line JSON processor. jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep, and friends let you play with text.
Example usage
$ cat azones.json
{ "availabilityZoneInfo": [ { "hosts": { "node-1.example.com": { "nova-compute": { "active": true, "available": true } }, "node-2.example.com": { "nova-compute": { "active": true, "available": true } } }, "zoneName": "az1", "zoneState": { "available": true } }, { "hosts": { "node-3.example.com": { "nova-compute": { "active": true, "available": true } }, "node-4.example.com": { "nova-compute": { "active": true, "available": true } } }, "zoneName": "az2", "zoneState": { "available": true } } ] }
- Capture just the availability zone names:
$ cat azones.json | jq '[.availabilityZoneInfo[] | .zoneName]'
[ "az1", "az2" ]
Or, for compact instead of pretty-printed output:
$ cat azones3.json | jq -c '[.availabilityZoneInfo[] | .zoneName]' ["az1","az2"]
- Capture just the hostname (e.g., "
node-1.example.com
") key for availability zone "az1":
$ cat azones.json | jq '[.availabilityZoneInfo[] | select(.zoneName == "az1") | {hosts: .hosts|keys}]'
[ { "hosts": [ "node-1.example.com", "node-2.example.com" ] } ]
Or, for a more script-friendly output:
$ cat azones.json | jq -cM '[.availabilityZoneInfo[] | select(.zoneName == "az1") | {hosts: .hosts|keys}]' | sed -e 's/["}\[]//g;s/\]//g;s/{hosts://g;s/,/ /g' #~OR~ $ foo=($(cat azones3.json | jq -cM '[.availabilityZoneInfo[] | select(.zoneName == "az1") | {hosts: .hosts|keys}]' | sed -e 's/["}\[]//g;s/\]//g;s/{hosts://g;s/,/ /g')) $ echo ${foo[0]} #=> node-1.example.com
- Get just the raw values:
$ echo '{ "packet_loss": [ {"ips": "10.0.0.10 10.0.0.11 10.0.0.12", "node-17": "3/3" }] }' | jq -r '[.packet_loss[] | .ips] | .[]' 10.0.0.10 10.0.0.11 10.0.0.12