Use jq to output a flat array of JSON objects nested anywhere within source document

Viewed 116

I'd like to select/identity-output all objects in arrays under "emp" keys into a flat array of those objects.

[
  {
    "eng": {
      "dev": {
        "dir": {
          "name": "Mickey"
        },
        "emp": [
          {
            "name": "Goofy",
            "job": "laugh",
            "start": "today"
          },
          {
            "name": "Minnie",
            "job": "laugh"
          }
        ]
      }
    }
  },
  {
    "mgmt": {
      "dir": {
        "name": "Donald"
      },
      "emp": [
        {
          "name": "Woody",
          "job": "smile"
        },
        {
          "name": "Buzz",
          "job": "smile"
        }
      ]
    }
  }
]

I'm looking for a flat array of arbitrary objects found in arbitrary locations within the document (in this example, under "emp" parent/keys).

In this example, it would look like

[
  {
    "name": "Goofy",
    "job": "laugh",
    "start": "today"
  },
  {
    "name": "Minnie",
    "job": "laugh"
  },
  {
    "name": "Woody",
    "job": "smile"
  },
  {
    "name": "Buzz",
    "job": "smile"
  }
]

I've looked through a lot of documentation and am able to do this if I know in advance precisely where these 'emp' keys are in the document, but not if they're distributed through the document at a priori unknown locations/paths.

1 Answers

Use recurse to walk the structure. From all the substrucures, select objects with the emp key. Output the corresponding values and merge the resulting arrays.

jq '[recurse | select (type == "object" and .emp) | .emp ] | add' file.json
Related