Home > database >  Flatten or "explode" an array-valued field, in an array of objects?
Flatten or "explode" an array-valued field, in an array of objects?

Time:12-02

I have this data:

[
  { "path": "x", "types": ["a", "b"] },
  { "path": "y", "types": ["c", "d"] }
]

And I am looking to obtain this output:

{ "path": "x", "type": "a" }
{ "path": "x", "type": "b" }
{ "path": "y", "type": "c" }
{ "path": "y", "type": "d" }

How would I do this with Jq?

CodePudding user response:

Try

.[] | {path, type: .types[]}
{"path":"x","type":"a"}
{"path":"x","type":"b"}
{"path":"y","type":"c"}
{"path":"y","type":"d"}

Demo

Use the --compact-output or -c option to also have the same compact formatting.


Edit:

This is documented in the manual under the heading "Object Construction: {}". Specifically the statement, "If one of the expressions produces multiple results, multiple dictionaries will be produced."

Thanks to @shadowtalker for looking it up.

  • Related