519dsd
519dsd

Reputation: 17

jq - how to select nested objects in a single array

I have a JSON file with multiple objects within multiple arrays, like below

[
  [
    {
      "instance_id": "i-35345353453",
      "account": "12344",
      "az": "ca-central-1a"
    },
    {
      "instance_id": "i-35345353453",
      "account": "12344",
      "az": "ca-central-1b"
    }
  ],
  [
    {
      "instance_id": "i-35345353453",
      "account": "12344",
      "az": "us-east-1d"
    },
    {
      "instance_id": "i-35345353453",
      "account": "12344",
      "az": "us-east-1d"
    }
  ],
  [
    {
      "instance_id": "i-35343453453",
      "account": "12344",
      "az": "eu-central-1a"
    }
  ]
]

I want the output to be a single array with all the nested objects, like below. Using the JSON input above, how do you use jq to produce the following output?

[
{
  "instance_id": "i-35345353453",
  "account": "12344",
  "az": "ca-central-1a"
},
{
  "instance_id": "i-35345353453",
  "account": "12344",
  "az": "ca-central-1b"
},
{
  "instance_id": "i-35345353453",
  "account": "12344",
  "az": "us-east-1d"
},
{
  "instance_id": "i-35345353453",
  "account": "12344",
  "az": "us-east-1d"
},
{
  "instance_id": "i-35343453453",
  "account": "12344",
  "az": "eu-central-1a"
}
]

How to get this done in JQ? Thanks in advance.

Upvotes: 0

Views: 854

Answers (2)

pii_ke
pii_ke

Reputation: 2881

Just use the flatten filter. See demo with your data: https://jqplay.org/s/kBxBJLxDKH

You can use it in a command like: jq flatten input_file.

Upvotes: 1

hobbs
hobbs

Reputation: 239712

[ .[][] ] works for your example (go down two levels from the root and put everything found into an array), or perhaps [ .. | objects ], which is insensitive to the depth of the array nesting (but does assume that none of your objects contain sub-objects... it just finds all objects at any depth).

Upvotes: 0

Related Questions