To keep things simple, I have that file.js:
{
"devices": [
{
"label": "label1",
"percent": 10
},
{
"label": "label2",
"percent": 20
}
]
}
Since I browsed Google and StackOverflow a lot, I actually know how to update, let's say, the label2 from 20% to 50% :
jq '.devices[] | select(.label == "label2").percent = 50' file.json
But here's the ouput:
{
"label": "label1",
"percent": 10
}
{
"label": "label2",
"percent": 50
}
The devices object (?) is not there anymore.
I'd like to find a way to keep the exact same input format. I guess I should rid of the pipe, but I don't know how. I've browsed Google and I found the to_entries / with_entries / from_entries, that seem to keep the whole thing, but I don't know how to merge eveything together.
Thank you.
CodePudding user response:
Make the traversal and filtering all part of the assignment's LHS using parentheses:
jq '(.devices[] | select(.label == "label2").percent) = 50' file.json
Alternatively, update |=
to a map
of the whole .devices
array:
jq '.devices |= map(select(.label == "label2").percent = 50)' file.json
Output:
{
"devices": [
{
"label": "label1",
"percent": 10
},
{
"label": "label2",
"percent": 50
}
]
}