Reputation: 360
I have the following JSON:
{
"field1":"foo",
"array":[
{
child_field1:"c1_1",
child_field2:"c1_2"
},
{
child_field1:"c2_1",
child_field2:"c2_2"
}
]...
}
and using jq
, I would like to return the following output, where the value of field1
is repeated for every child element.:
foo,c1_1,c1_2
foo,c2_1,c2_2
...
I can access each field separately, am having trouble returning the desired result above.
Can this be done with jq?
Upvotes: 1
Views: 205
Reputation: 92854
jq
solution:
jq -r '.field1 as $f1 | .array[]
| [$f1, .[]]
| join(",")' input.json
The output:
foo,c1_1,c1_2
foo,c2_1,c2_2
Upvotes: 0
Reputation: 116640
In cases like this, there's no need for reduce
or `to_entries', or to list the fields explicitly -- one can simply exploit jq's backtracking behavior:
.field1 as $f
| .array[]
| [$f, .[]]
| @csv
As pointed out by @MatthewLDaniel, there are many alternatives to using @csv here.
Upvotes: 0
Reputation: 33158
jq -r '.array[] as $a | [.field1, $a.child_field1, $a.child_field2] | @csv'
Does the right thing for the sample data you provided, but I freely admit there are lots of ways to do that kind of thing in jq
, and that was only the first one which sprang to mind.
I fed it through @csv
because it seemed like that was what you wanted, but if you prefer the actual output, exactly as you have written, then:
jq -r '.array[] as $a | "\(.field1),\($a.child_field1),\($a.child_field2)"'
will produce it
Upvotes: 3