Jq

From Christoph's Personal Wiki
Revision as of 02:06, 15 January 2016 by Christoph (Talk | contribs) (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...")

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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

External links