Home > Net >  How to bring outer values inside an array iteration
How to bring outer values inside an array iteration

Time:04-02

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?

CodePudding user response:

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])'

Demo

Or create completely new objects from data collected:

jq 'map(.a as $a | [.b[] as $b | {$a,$b}])'

Demo

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

CodePudding user response:

Try this :

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

As @pmf pointed out, you can also update object :

jq 'map([.b=.b[]])'
  • Related