使用jq更新数组时终端报错,在线JQ Playground正常问题排查
问题:终端执行jq命令修改JSON时出错,在线环境却正常?
原始JSON文件(temp.json)内容:
{ "first": { "second": [ { "third": [ "1000", "1001" ], "fourth": "Don'tWantToChange" }, { "third": [ "1000", "1001", "1002" ], "fourth": "WantToChange" } ] } }
期望修改后的JSON:
{ "first": { "second": [ { "third": [ "1000", "1001" ], "fourth": "Don'tWantToChange" }, { "third": [ "1000", "1001", "1002" ], "fourth": "changed" } ] } }
使用的jq命令:
jq '(.first | .second[] | select(.third | index("1002")) | .fourth) |= "changed"' temp.json
终端执行时报错:
jq: error (at temp.json:13): Invalid path expression near attempt to access element "fourth" of {"third":["1000","1001","1...
解决方案
问题出在jq版本差异:在线JQ Playground一般用的是较新版本jq,而你终端里的jq版本偏旧,旧版本不支持这种通过管道串联数组遍历和筛选的路径写法。
修正后的命令有两种可选写法:
写法一(简化路径,兼容多数版本)
jq '(.first.second[] | select(.third | index("1002"))).fourth = "changed"' temp.json
去掉赋值运算符|=前的多余管道嵌套,直接通过.first.second[]遍历数组,筛选出目标元素后直接修改.fourth字段。
写法二(兼容性最强,适配所有jq版本)
jq '.first.second |= map(if .third | index("1002") then .fourth = "changed" else . end)' temp.json
用map遍历数组,对每个元素做条件判断:如果.third包含"1002"就修改.fourth,否则保持原元素不变,这种写法逻辑更清晰,几乎适配所有jq版本。
内容的提问来源于stack exchange,提问作者Amin SZ
相关产品推荐
相关产品推荐

