使用jq展平JSON文档

时间:2014-07-11 12:49:57

标签: json jq

我正在考虑以下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"。我该怎么办?目前我对命令行工具很感兴趣,但我也对其他建议持开放态度。

4 个答案:

答案 0 :(得分:30)

这是一个棘手的工艺。

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

答案 1 :(得分:4)

您可以使用此过滤器:

[.[] | {index: .index, type: .type, id: .id, deviceOs: .fields.deviceOs[],deviceID: .fields.deviceID[],country: .fields.country[]}]

您可以在这里测试https://jqplay.org

答案 2 :(得分:1)

以下是一些变体,首先将.fields合并到包含对象中,然后展开数组元素。首先,我们用

来处理.fields
  .[]
| . + .fields
| del(.fields)

给我们留下了像

的对象
{
  "index": "index1",
  "type": [
    "type"
  ],
  "id": "id1",
  "deviceOs": [
    "Android"
  ],
  "deviceID": [
    "deviceID1"
  ],
  "country": [
    "DE"
  ]
}
然后我们可以多种方式压扁键。 一种方法是使用 with_entries

| with_entries( .value = if .value|type == "array" then .value[0] else .value end )

另一种方法是使用 reduce setpath

| . as $v
| reduce keys[] as $k (
    {};
    setpath([$k]; if $v[$k]|type != "array" then $v[$k] else $v[$k][0] end)
  )

答案 3 :(得分:1)

有一个名为gron的工具,您可以将其插入json,以获得类似的内容。

$ gron document.json
json = [];
json[0] = {};
json[0].fields = {};
json[0].fields.country = [];
json[0].fields.country[0] = "DE";
json[0].fields.deviceID = [];
json[0].fields.deviceID[0] = "deviceID1";
json[0].fields.deviceOs = [];
json[0].fields.deviceOs[0] = "Android";
json[0].fields.type = [];
json[0].fields.type[0] = "type";
json[0].id = "id1";
json[0].index = "index1";
json[0].type = "type1";
json[1] = {};
json[1].fields = {};
json[1].fields.country = [];
json[1].fields.country[0] = "US";
json[1].fields.deviceID = [];
json[1].fields.deviceID[0] = "deviceID2";
json[1].fields.deviceOs = [];
json[1].fields.deviceOs[0] = "Android";
json[1].fields.type = [];
json[1].fields.type[0] = "type";
json[1].id = "id2";
json[1].index = "index2";
json[1].type = "type2";