使用jq展平JSON文档 [英] Flatten a JSON document using jq

查看:85
本文介绍了使用jq展平JSON文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm considering the following array of JSON objects:

[
  {
    "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".我该怎么办?目前,我对命令行工具很感兴趣,但是我也欢迎其他建议.

I'm trying to work with jq but I fail to flatten the "fields". How should I do it? At the moment I'm interested in command-line tools, but I'm open to other suggestions as well.

推荐答案

这是一个棘手的问题.

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

我们将其分解并解释其内容

Let's break it down and explain the bits of it

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

  1. For every item in the array...

map(...)

  • 创建一个新对象,其中包含除fields属性以外的所有值.

  • Create a new object containing the values for all except the fields property.

    with_entries(select(.key != "fields"))
    

  • 用...组合……

  • Combine that with...

    +
    

  • 每个fields都将每个值投影到每个数组的第一项

  • Each of the fields projecting each of the values to the first item of each array

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

  • 这篇关于使用jq展平JSON文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆