替换其他键所在的值 - jq

Replace values where other keys are - jq

我对这个 jq 命令有点迷茫。我有一个这样的 json 文件:

...

{
    "class": "classOne",
    "title": "title1",
    "text": "text1"
},
{
    "class": "classTwo",
    "title": "title2",
    "text": "text2"
},

...

我想做的是根据 title.

的值将 texts 的值替换为另一个值

我该怎么做,一般情况下如何根据同一 'group' 中的另一个值替换一个值?另外,我可以按照 sed'.../g' 一起使用的方式指定 'only first' 或 'general' 吗?


编辑

我希望能够使用我的 json 的任何深度,这就是为什么我包含的代码不是很大。基本上我想根据另一个键的值修改一个值 always in the same object.


Tyvm.

假设 .text 的新值取决于 same JSON 对象中的 .title,您可以遵循的一个模型是:

map(if .title | test("REGEX") then .text = ... else ... end)

jq 同时具有 sub(类似于 sed 的 's',但默认情况下没有“g”)和 gsub(类似于 sed 的 's',但带有“g”), 根据 https://stedolan.github.io/jq/manual/#RegularexpressionsPCRE

的 jq 手册

使用walk/1

如果您想更改所有带有 .title 和 .text 的对象,您可以使用 walk/1 以下行:

walk(if type == "object" and has("title") and has("text")
     then if .title | test("REGEX") then .text = ... else ... end
     else . end)

@Arainty 编辑: 使用 test 只是为了说明;使用 == 匹配精确值。 (.title=="STRING")