jq - flatten parent objects into children

Viewed 494

I have the following source JSON which I need to reshape:

{
  "group": "A",
  "name": "abc",
  "events": [
    {
      "id": "54209",
      "message": "foobar 1"
    },
    {
      "id": "76548",
      "message": "foobar 2"
    }
  ]
}
{
  "group": "B",
  "name": "def",
  "events": [
    {
      "id": "54593",
      "message": "foobar 3"
    },
    {
      "id": "20359",
      "message": "foobar 4"
    }
  ]
}

How can I get to the following output:

[
  {
    "group": "A",
    "name": "abc",
    "id": "54209",
    "message": "foobar 1"
  },
  {
    "group": "A",
    "name": "abc",
    "id": "76548",
    "message": "foobar 2"
  },
  {
    "group": "B",
    "name": "def",
    "id": "54593",
    "message": "foobar 3"
  },
  {
    "group": "B",
    "name": "def",
    "id": "20359",
    "message": "foobar 4"
  }
]

I basically want a single array with all the child event arrays, but with their parent objects embedded into them. I came very close with an example from this issue: https://github.com/stedolan/jq/issues/646. But I need the keys as well, not just the values.

2 Answers

Copy all fields except events from the root to each event, and put resulting objects into an array.

jq -n '[ inputs | .events[] + del(.events) ]'

Online demo

Almost same logic as Oguz's answer, using with_entries() to remove events from root and adding the fields alone

jq -n '[ inputs | with_entries(select(.key != "events")) + (.events[]) ]'

jqplay - Demo

Related