【问题标题】:How do I set multiple path values in jq at once?如何一次在 jq 中设置多个路径值?
【发布时间】:2023-04-04 00:06:01
【问题描述】:

我已经知道如何使用setpath 在我的 JSON 文件 package.json 中设置一个值。我可以使用模式来做到这一点吗?

cat package.json | jq 'setpath(["dependencies", "acme-a"]; "mytagname")'

我想做的是使用如下模式,因此它还将路径设置为“acme-b”、“acme-c”等:

cat package.json | jq 'setpath(["dependencies", "acme-*"]; "mytagname")'

jq 是否支持,如果支持,它是如何实现的?

【问题讨论】:

  • package.json的内容是什么,需要本地复现
  • @Inian 为此,假设它看起来像 {"dependencies": {"acme-a": "1.0.0", "acme-b": "2.0.0", "acme-c": "3.0.0"} }

标签: json path edit reduce jq


【解决方案1】:
.dependencies |= with_entries(
  if .key|test("^acme-") then .value = "mytagname" else . end )

也可以使用“startswith”。使用“walk”可能比较合适。

要使用“setpath”,可以使用“reduce”(例如使用“paths”),例如:

reduce paths as $p (.;
  if $p[-1] | test("^acme-") then setpath($p; "mytagname") else . end)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-14
    • 2017-07-23
    • 2022-01-18
    • 2016-02-17
    • 2021-11-02
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    相关资源
    最近更新 更多