json - 替换其他键所在的值 - jq
问题描述
我对这个jq
命令有点迷茫。我有一个json
这样的文件:
...
{
"class": "classOne",
"title": "title1",
"text": "text1"
},
{
"class": "classTwo",
"title": "title2",
"text": "text2"
},
...
我要做的是text
用另一个值替换 s 的值,具体取决于title
.
我该怎么做,一般来说,我如何根据同一“组”中的另一个值替换一个值?另外,我可以按照使用的方式指定“仅第一个”或“一般”sed
吗'.../g'
?
编辑
我希望能够使用我的任何深度json
,这就是我包含的代码不是很大的原因。基本上我想根据总是在同一个对象中的另一个键的值来修改一个值。
特维姆。
解决方案
假设 .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"
)
推荐阅读
- angular - Dspace 不加载
- python - 侦听已在使用的 UDP 端口 Python
- google-kubernetes-engine - 如何在 botfront helm 中设置主机并在 kubernetes 中更新参数
- bigcommerce - BigCommerce Stencil - 使用前端的 GraphQL 查询不返回任何内容
- wordpress - WordPress 下载文件而不是在浏览器中打开
- r - 使用条件创建新列
- javascript - 使用 React JS 从 firebase 存储下载音频文件
- accelerometer - 如何将 6 个加速度脉冲转换为刚体的 3 个平移和 3 个旋转运动?
- vue.js - 有没有办法在 Vuetify-jsonschema-form Vue js 中更改步进表单的图标?
- xml - 将变量分配给 Python 文件名