【问题标题】:Replace array values if they exist with jq如果数组值存在,则用 jq 替换它们
【发布时间】:2021-04-06 16:29:53
【问题描述】:

虽然我经常使用jq,但我这样做主要是为了完成更简单的任务。这把我的脑子打成了一个结。

我有一些来自单元测试的 JSON 输出需要修改。具体来说,我需要删除(或替换)一个错误值,因为测试框架会生成数百行长的输出。

JSON 看起来像这样:

{
  "numFailedTestSuites": 1,
  "numFailedTests": 1,
  "numPassedTestSuites": 1,
  "numPassedTests": 1,
  ...
  "testResults": [
    {
      "assertionResults": [
        {
          "failureMessages": [
            "Error: error message here"
          ],
          "status": "failed",
          "title": "matches snapshot"
        },
        {
          "failureMessages": [
            "Error: another error message here",
            "Error: yet another error message here"
          ],
          "status": "failed",
          "title": "matches another snapshot"
        }
      ],
      "endTime": 1617720396223,
      "startTime": 1617720393320,
      "status": "failed",
      "summary": ""
    },
    {
      "assertionResults": [
        {
          "failureMessages": [],
          "status": "passed",
        },
        {
          "failureMessages": [],
          "status": "passed",
        }
      ]
    }
  ]
}

我想将 failureMessages 中的每个元素替换为通用的 failed 消息或自身的截断版本(比如说 100 个字符)。

(对我而言)棘手的部分是 failureMessages 是一个数组,可以有 0-n 个值,我需要修改所有这些值。

我知道我可以找到带有 select(.. | .failureMessages | length > 0) 的非空数组,但仅此而已,因为我实际上不需要 select 项目,我需要替换它们并取回完整的 JSON。

【问题讨论】:

    标签: arrays json jq edit


    【解决方案1】:

    最简单的解决方案是:

    .testResults[].assertionResults[].failureMessages[] |= .[0:100]
    

    查看online

    在线示例仅保留失败消息的前 10 个字符,以显示对您在问题中发布的示例 JSON 的影响(它包含简短的错误消息)。

    在 JQ 文档中了解 array/string slice (.[a:b])update assignment (|=)

    【讨论】:

    • 哇!我还不知道.[0:100] 子字符串表示法。而且我不知道它像[] |= 一样简单。谢谢!在我花了 2 个小时做这件事后,你才挽救了我的理智!
    • @peak 上面写着“10 个字符”的文字是关于 jqplay 示例的。该问题询问如何将错误消息截断为 100 个字符,但示例 JSON 不包含那么大的错误消息。
    猜你喜欢
    • 1970-01-01
    • 2019-08-11
    • 2021-09-01
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-19
    • 2010-09-20
    相关资源
    最近更新 更多