I have an array of JSON objects, and I am trying change the name
and version
on the object of a given @type
, with the following input
[
{
"name": "oldname",
"version": "oldversion",
"@type": "Project"
},
{
"name": "bomname",
"version": "bomversion",
"@type": "BOM"
},
{
"name": "componentname",
"version": "componentversion",
"@type": "Component"
}
]
I found many examples for changing a single value, and I can successfully do this by chaining multiple select
statements together.
$ cat original.json | jq '[ .[] | (select(.["@type"] == "Project") | .name ) = "newname" | (select(.["@type"] == "Project") | .version ) = "newversion ] ' > renamed.json
But I was hoping I could condense this so I only have perform the select
once to change both values.
Using your approach:
[ .[]
| if .["@type"] == "Project"
then .name = "newname" | .version = "newversion"
else . end ]
or if you want to use select
, you could write:
map( (select(.["@type"] == "Project") | .name = "newname" | .version = "newversion" ) // .)
or more exotically:
(.[] | select(["@type"] == "Project"))
|= (.name = "newname" | .version = "newversion" )
将对象与新值合并。
map(select(.["@type"] == "Project") * {name: "newname", version: "newversion"} // .)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.