Reputation: 3
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.
Upvotes: 0
Views: 2117
Reputation: 134881
Merge an object with the new values.
map(select(.["@type"] == "Project") * {name: "newname", version: "newversion"} // .)
Upvotes: 1
Reputation: 116750
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" )
Upvotes: 2