SSh
SSh

Reputation: 13

How can you filter on "Keys" using jq?

I am looking to filter a JSON stream based on its keys. Here is the public JSON file: https://s3.amazonaws.com/okta-ip-ranges/ip_ranges.json that I am trying to wrangle. When I filter this for keys jq 'keys', I get the following output

[
  "apac_cell_1",
  "emea_cell_1",
  "emea_cell_2",
  "preview_cell_1",
  "preview_cell_2",
  "preview_cell_3",
  "us_cell_1",
  "us_cell_10",
  "us_cell_11",
  "us_cell_12",
  "us_cell_2",
  "us_cell_3",
  "us_cell_4",
  "us_cell_5",
  "us_cell_6",
  "us_cell_7"
]

I am trying to get all the ip_ranges associated with the keys starting with "us_cell_*" and I have not found a way to do it. Most of the filtering seems to be focused on the values and not the keys.

Upvotes: 1

Views: 2971

Answers (1)

Aaron
Aaron

Reputation: 24812

You can use the following :

to_entries | map(select(.key | startswith("us_cell_")) | .value.ip_ranges) | add

Try it here.

to_entries maps the root object into an array of objects with key and value fields corresponding to the fields of the original object.

We filter that to retain only those which have a key starting with "us_cell_", map it further to keep only the ip ranges and finally merge those arrays together.

Upvotes: 4

Related Questions