繁体   English   中英

如何在 shell 脚本中的 json 文件中将 jq 数组值组合成相同的键?

[英]How to combine jq array value into same key in json file in shell script?

我有一个包含以下内容的 json 文件:

[
  {
    "id": "one",
    "msg": [
      "test"
    ],
    "FilePath": [
      "JsonSerializer.cs",
      "ChatClient.cs",
      "MiniJSON.cs"
    ],
    "line": [
      358,
      1241,
      382
    ]
  },
  {
    "id": "two",
    "msg": [
      "secondtest"
    ],
    "FilePath": [
      "Utilities.cs",
      "PhotonPing.cs"
    ],
    "line": [
      88,
      36
    ]
  }
]

我想要 output ,你可以看到值合并为一个:

one
[
  "test"
]
[
  "JsonSerializer.cs",358
  "ChatClient.cs",1241
  "MiniJSON.cs",382
]

two
[
  "secondtest"
]
[
  "Utilities.cs",88
  "PhotonPing.cs",36
]

我试过这个cat stack.json |jq -r '.[]|.id,.msg,.FilePath,.line'给 output 作为

  one
    [
      "test"
    ]
    [
      "JsonSerializer.cs",
      "ChatClient.cs",
      "MiniJSON.cs"
    ]
    [
      358,
      1241,
      382
    ]
    two
    [
      "secondtest"
    ]
    [
      "Utilities.cs",
      "PhotonPing.cs"
    ]
    [
      88,
      36
    ]

请帮我解决这个问题,我已经尝试了很多调试但无法通过。 此外,每个文件路径和行总是相似的。 例如,如果 FilePath 有 3,则 line 也有 3 个值。

您正在寻找transpose

.[] | .id, .msg, ([.FilePath, .line] | transpose | add), ""

在线演示

<stack.json jq -r '.[] | .id, .msg, ([.FilePath, .line]|transpose|add)'

根据您的要求提供 output。

transpose[[1,2,3],[4,5,6]]转换为[[1,4],[2,5],[3,6]] add所有数组元素收集到一个数组中。

如果您希望在一行中包含文件路径和行号,我建议将它们格式化为字符串,用冒号分隔:

.[] | .id, .msg, ([.FilePath, .line]|transpose|map(join(":")))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM