jq:避免嵌套数组映射

jq: avoid nested array mapping

这是我的文档:

{
  "_id": "a6c8004c-efdc-4462-b474-31df2d417be3",
  "address": [
    {
      "city": {
        "value": "2505300"
      },
      "state": {
        "value": "25"
      },
      "postalCode": {
        "value": "25132"
      }
    }
  ]
}
{
  "_id": "aa4b4ba9-32e3-4384-8cd8-0852bae0029b",
  "address": [
    {
      "city": {
        "value": "2521700"
      },
      "state": {
        "value": "25"
      },
      "postalCode": {
        "value": "25300"
      }
    }
  ]
}

目前,我正在应用这个 JQ 过滤器:

def pick_address:
    {
        city: .city | .value,
        postalCode: .postalCode | .value,
        state: .state | .value
    };

map(.address | map(pick_address))

我明白了:

[
  [
    {
      "city": "2505300",
      "postalCode": "25132",
      "state": "25"
    }
  ],
  [
    {
      "city": "2521700",
      "postalCode": "25300",
      "state": "25"
    }
  ]
]

如您所见,我正在获取带有嵌套数组的对象。

我需要将其获取为:

[
  {
    "city": "2505300",
    "postalCode": "25132",
    "state": "25"
  },
  {
    "city": "2521700",
    "postalCode": "25300",
    "state": "25"
  }
]

我不太明白哪里出了问题。

有什么想法吗?

而不是将 pick_address 映射到 address 数组

map(.address | map(pick_address))

直接将它应用到它的元素上:

map(.address[] | pick_address)

Demo

旁注:如果在 pick_address 中将操作 .value 应用于 all 字段,则 def pick_address: map_values(.value); 将等效. Demo

这样做是不是更简单?

jq '.[].address[] | [{city: .city.value, state: .state.value, postalCode: .postalCode.value}]'

没有任何硬编码键的更动态的解决方案,使用

jq --slurp 'map(.address[] | with_entries(.value |= .value))'

会产生

[
  {
    "city": "2505300",
    "state": "25",
    "postalCode": "25132"
  },
  {
    "city": "2521700",
    "state": "25",
    "postalCode": "25300"
  }
]

你可以在这个online demo

中测试