使用jq展平JSON文档

德罗

我正在考虑以下JSON对象数组:

[
  {
    "index": "index1",
    "type": "type1",
    "id": "id1",
    "fields": {
      "deviceOs": [
        "Android"
      ],
      "deviceID": [
        "deviceID1"
      ],
      "type": [
        "type"
      ],
      "country": [
        "DE"
      ]
    }
  },
  {
    "index": "index2",
    "type": "type2",
    "id": "id2",
    "fields": {
      "deviceOs": [
        "Android"
      ],
      "deviceID": [
        "deviceID2"
      ],
      "type": [
        "type"
      ],
      "country": [
        "US"
      ]
    }
  }
]

我想将其展平以获得:

[
  {
    "index": "index1",
    "type": "type",
    "id": "id1",
    "deviceOs": "Android",
    "deviceID": "deviceID1",
    "country": "DE"
  },
  {
    "index": "index2",
    "type": "type",
    "id": "id2",
    "deviceOs": "Android",
    "deviceID": "deviceID2",
    "country": "US"
  }
]

我正在尝试与之合作,jq但未能将其压平"fields"我该怎么办?目前,我对命令行工具很感兴趣,但是我也欢迎其他建议。

杰夫·梅卡多(Jeff Mercado)

这是一个棘手的技巧。

map
(
    with_entries(select(.key != "fields"))
    +
    (.fields | with_entries(.value = .value[0]))
)

让我们分解一下,并解释其中的一些内容

  1. 对于数组中的每个项目...

    map(...)
    
  2. 创建一个新对象,其中包含除fields属性之外的所有值

    with_entries(select(.key != "fields"))
    
  3. 结合...

    +
    
  4. 每个将fields每个值投影到每个数组的第一项

    (.fields | with_entries(.value = .value[0]))
    

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章