为什么在使用jq更新数组时会显示错误?

huangapple go评论68阅读模式
英文:

Why it shows error While updating an array using jq

问题

这是我的代码:

jq '(.first | .second[] | select(.third | index("1002")) | .fourth) |= "changed"' temp.json


它在在线JQ Playgrounds上完美运行,但在终端中显示错误:

jq: error (at temp.json:13): Invalid path expression near attempt to access element "fourth" of {"third":["1000","1001","1...


我哪里错了?
英文:

My JSON file (temp.json):

{
	"first": {
		"second": [
			{
				"third": [
					"1000",
					"1001"
				],
				"fourth": "Don'tWantToChange"
			},
			{
				"third": [
					"1000",
					"1001",
					"1002"
				],
				"fourth": "WantToChange"
			}
		]
	}
}

I want to select an item from array and update as below

{
	"first": {
		"second": [
			{
				"third": [
					"1000",
					"1001"
				],
				"fourth": "Don'tWantToChange"
			},
			{
				"third": [
					"1000",
					"1001",
					"1002"
				],
				"fourth": "changed"
			}
		]
	}
}

This is my code:

jq '(.first | .second[] | select(.third | index("1002")) | .fourth) |= "changed"' temp.json

It works on Online JQ Playgrounds perfectly

But in the terminal, it shows Error:

jq: error (at temp.json:13): Invalid path expression near attempt to access element "fourth" of {"third":["1000","1001","1...

Where am I going wrong?

答案1

得分: 2

jq-1.5-1-a5b5cbe(在某些Debian和Ubuntu的特定版本中打包)存在从管道化的 select 过滤器中推断类型的问题。在这种情况下,如果值未找到,index 提供 null,如果找到了,它提供一个数字(实际索引),但 select 在其主体中需要一个布尔结果。

解决方法:将主体用括号括起来,然后将其结果与 null 进行比较以获得布尔值:

(.first | .second[] | select((.third | index("1002")) != null) | .fourth) = "changed"

解决方案:升级到 jq 1.6。它于2018年发布。

注意:对于给定的示例,无论哪个版本都不需要更新操作符 |=。只需使用 = 来分配一个静态值。

英文:

jq-1.5-1-a5b5cbe (as packaged with certain releases of Debain and Ubuntu) had issues with inferring types from a pipelined select filter. In this case, index provides null if the value was not found, or a number (the actual index) if it was, but select requires a boolean result in its body.

Workaround: Wrap the body in parens, and compare its result against null to get a boolean:

(.first | .second[] | select((.third | index("1002")) != null) | .fourth) = "changed"

Solution: Upgrade to jq 1.6. It was released in 2018.

Note: With the given sample, neither version requires the update operator |=. Just use = to assign a static value.

huangapple
  • 本文由 发表于 2023年6月30日 01:23:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76583318.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定