'How to bring outer values inside an array iteration
I have a JSON in the shape
[
{
a:1,
b: [2,3]
},
{
a:4,
b: [5,6]
}
]
That I want to transform in the shape
[
[
{
a: 1,
b: 2,
},
{
a: 1,
b: 3,
},
],
[
{
a: 4,
b: 5,
},
{
a: 4,
b: 6,
},
],
]
That is I want to bring the value of the field a inside the array.
how can I do this with jq?
Solution 1:[1]
Try this :
jq 'map([{a,b:.b[]}])'
As @pmf pointed out, you can also update object :
jq 'map([.b=.b[]])'
Solution 2:[2]
You could iterate over the items using variable binding with as.
Then either update .b to have the value of its items using the update operator |=:
jq 'map([.b[] as $b | .b |= $b])'
Or create completely new objects from data collected:
jq 'map(.a as $a | [.b[] as $b | {$a,$b}])'
[
[
{
"a": 1,
"b": 2
},
{
"a": 1,
"b": 3
}
],
[
{
"a": 4,
"b": 5
},
{
"a": 4,
"b": 6
}
]
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
