Reputation: 189
Hello I want to change each json object key value. JSON -
abc='[{"fn": 1,"name":"raimonds"},{"fn": 2,"name":"john"}]'
Now using some filter in jq -
res=$(echo "$abc" | jq 'map(if .fn then . + {"fn":22222} else . end)')
Now if I'm echoing $res it retuns -
'[{"fn": 22222,"name":"raimonds"},{"fn": 22222,"name":"john"}]'
I want to multiply each fn by 2 and output it like this -
abc='[{"fn": 22222,"name":"raimonds"},{"fn": 44444,"name":"john"}]'
How can i do that? Thank you!
Upvotes: 1
Views: 288
Reputation: 124734
Given:
res='[{"fn": 22222,"name":"raimonds"},{"fn": 22222,"name":"john"}]'
As @chepner pointed out, you could modify the object in a filter:
echo "$res" | jq '.[].fn *= 2'
Output:
[
{
"fn": 44444,
"name": "raimonds"
},
{
"fn": 44444,
"name": "john"
}
]
My original suggestion was to construct objects with the modified property, which would quickly get tedious, and has no advantages whatsoever:
echo "$res" | jq '[ .[] | {fn: (.fn * 2), name: .name} ]'
Upvotes: 1
Reputation: 14695
This filter multiplies the .fn
member of each object within an array (or another object) by 2, leaving other members unchanged.
.[].fn *= 2
Upvotes: 0