从嵌套数组内容创建文档

从嵌套数组内容创建文档

给定以下 JSON:

[
  {
    "command": "1",
    "response": [
      "a",
      "b",
      "c"
    ],
    "guild_id": "guild"
  },
  {
    "command": "1",
    "response": "d",
    "guild_id": "guild"
  },
]

如何使用 将其转换为以下内容jq

[
  {
    "command": "1",
    "response": "a",
    "guild_id": "guild"
  },
  {
    "command": "1",
    "response": "b",
    "guild_id": "guild"
  },
  {
    "command": "1",
    "response": "c",
    "guild_id": "guild"
  },
  {
    "command": "1",
    "response": "d",
    "guild_id": "guild"
  },
]

答案1

jq 'map(if (.response|type == "array") then .response = .response[] else . end)' file

response这测试顶级数组的每个元素中的条目的类型。如果它是一个数组,则该条目将被“分解”或为每个数组元素重复一次;否则,将保持原样。

给出问题中的数据(删除有问题的逗号)的结果:

[
  {
    "command": "1",
    "response": "a",
    "guild_id": "guild"
  },
  {
    "command": "1",
    "response": "b",
    "guild_id": "guild"
  },
  {
    "command": "1",
    "response": "c",
    "guild_id": "guild"
  },
  {
    "command": "1",
    "response": "d",
    "guild_id": "guild"
  }
]

同样的事情,但更神秘一些:

jq 'map(.response = .response[]? // .)' file

如果顶级数组的response条目是数组,则这会复制(与上面相同的含义)条目;否则,将保持原样。

相关内容