首页 > 解决方案 > 替换其他键所在的值 - jq

问题描述

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

...

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

...

我要做的是text用另一个值替换 s 的值,具体取决于title.

我该怎么做,一般来说,我如何根据同一“组”中的另一个值替换一个值?另外,我可以按照使用的方式指定“仅第一个”或“一般”sed'.../g'


编辑

我希望能够使用我的任何深度json,这就是我包含的代码不是很大的原因。基本上我想根据总是在同一个对象中的另一个键的值来修改一个值。


特维姆。

标签: jsonjqgsub

解决方案


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

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

根据https://stedolan.github.io/jq/manual上的 jq 手册, jq 既有sub(如 sed 的 's',但默认情况下没有“g”)和gsub(如 sed 的's',但有“g”)/#正则表达式PCRE

使用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")


推荐阅读