Goddy
Goddy

Reputation: 44

JQ - map an array changing existing properties only, leaving others intact

Considering the following json:

[
    {
        "propertyA": 11,
        "nestedPropertyB": [ 12 ]
    },
    {
        "propertyA": 21
    }
]

I would like to get the following result:

[
    {
        "propertyA": 11,
        "propertyB": 12
    },
    {
        "propertyA": 21,
        "propertyB": null
    }
]

I would expect here to use array streaming, however it had not worked for me. Using:

jq "map({propertyB: .nestedPropertyB[]} + . | del(.nestedPropertyB))"

Resulted in exception:

jq: error (at <stdin>:10): Cannot iterate over null (null)

But when I had used nullable array streaming, the second object got discarded.

jq "map({propertyB: .nestedPropertyB[]?} + . | del(.nestedPropertyB))"

resulted in:

[
    {
      "propertyB": 2,
      "propertyA": 1
    }
]

I will appreciate helping me to solve this issue. JQ 1.6.

Upvotes: 0

Views: 200

Answers (1)

pmf
pmf

Reputation: 36326

You can use the alternative operator // to set a default value:

map({propertyA, propertyB: (.nestedPropertyB[]? // null)})
[
  {
    "propertyA": 11,
    "propertyB": 12
  },
  {
    "propertyA": 21,
    "propertyB": null
  }
]

Demo

Upvotes: 1

Related Questions