【问题标题】:jq - not working as expected in Jenkins shell scriptjq - 在 Jenkins shell 脚本中没有按预期工作
【发布时间】:2020-12-04 07:12:16
【问题描述】:

我将以下 JSON 命名为 my.json

[
  {
    "action": "copy",
    "artifact_location": "one foo one"
  },
  {
    "action": "copy",
    "artifact_location": "one bar one"
  },
  {
    "action": "remove",
    "artifact_location": "two foo two"
  }
]

我的目标是删除 所有 根 JSON 数组中的对象,如果 artifact_location 属性的一个对象包含字符串值 "foo"

我正在使用jq command line utility 来完成这项任务。 以下是我的 jq 命令。当我在本地机器上运行它时,它运行良好(macOS 和 jq 版本是 1.6)。

jq 'del(.[] | select(.artifact_location | test("foo")))' my.json

但是,当我尝试在 Jenkins 作业(Ubuntu 和 jq 版本为 1.3)中将上述命令作为 shell 脚本运行时,会出现以下错误。

error: test is not defined
del(.[] | select(.artifact_location | test("foo")))
                                      ^^^^
1 compile error

我在这里可能做错了什么?

【问题讨论】:

  • 我想说升级到这台 Jenkins 机器的受支持和维护的发行版。 jq 1.3 可以追溯到 Ubuntu Trusty Tahr,即 End Of Life 自 2019-04-25。请参阅:help.ubuntu.com/community/EOL#Ubuntu_14.04_Trusty_Tahr 此 Jenkins 服务器甚至不再获得安全更新!
  • Lea 在我的评论上方所说的话。如果您必须使用 jq 1.3 执行此操作,请使用 contains 而不是 test
  • 不幸的是,在 Jenkins 中升级 jq 版本不是一种选择。非常感谢您提供如何在此类用例中使用 contains() 函数的示例。
  • @gayashanbc 最直接的替换是一对一替换:jq 'del(.[] | select(.artifact_location | contains("foo")))' my.json
  • @gayashanbc 尝试删除父对象,因为 jq 1.3 的行为似乎与 jq 1.6 或更高版本不同:jq 'del(.[] | select(.artifact_location | contains("foo")) | ..)' my.json

标签: bash shell jenkins jq


【解决方案1】:

test/0 用于测试字符串是否匹配特定的正则表达式,这在 jq 1.3 中不可用(如 cmets 中所述)。在这种情况下可以使用contains/1

del(.[] | select(.artifact_location | contains("foo")))

我宁愿将其视为过滤掉对象,而不是删除它们。选择不包含“foo”的对象。

map(select(.artifact_location | contains("foo") | not))

【讨论】:

    猜你喜欢
    • 2014-05-07
    • 2019-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    • 2012-05-10
    • 2022-12-17
    • 2015-06-23
    相关资源
    最近更新 更多