Carl henderson
Carl henderson

Reputation: 76

How do I transform this JSON data using JQ to extract each nested array element to the top level in turn?

Given input of the form

[
    {"a": 1, "b": [{"c": 1}, {"c": 2}]}, 
    {"a": 2, "b": [{"c": 4}, {"c": 5}]}
]

I'm trying to transform to look like:

[
    {"a": 1, "b": [{"c": 1}],
    {"a": 1, "b": [{"c": 2}],
    {"a": 2, "b": [{"c": 3}],
    {"a": 2, "b": [{"c": 4}]
]

I have [map(.b) ] | flatten, however any further operation using the parent context does not seems to be possible. I'm really stuck and would appreciate any help.

Thanks

Upvotes: 1

Views: 78

Answers (2)

peak
peak

Reputation: 116670

Here's a straightforward solution that makes no mention of any keys besides "b":

map(. + (.b[] | {b: [.]}))

Upvotes: 1

oliv
oliv

Reputation: 13239

You can try this filter:

jq 'map({a,"b":.b[]|[.]})' file

It updates the content of b with each value of c separately.

Upvotes: 0

Related Questions