How to add an object to a list if it doesn't exist? #1716
Replies: 5 comments 3 replies
-
hi,i would like to know how to do this in multi commands? |
Beta Was this translation helpful? Give feedback.
-
You first query and in case it is not there you add. In bash it can be something like |
Beta Was this translation helpful? Give feedback.
-
You can do it like this:
Explanation:
|
Beta Was this translation helpful? Give feedback.
-
I know this is answered very elegantly, but I just came here and realized I had a different solution that may help someone (for me the following was simpler to reason about): yq '([{"name": "one", "value": "1"}] + .list | unique_by(.name)) as $uniqueList | .list = $uniqueList' file.yaml Explanation:
Note that this would remove existing duplicates as well, if you already have them in the original list (which you may or may not want). |
Beta Was this translation helpful? Give feedback.
-
Yet another take:
Which reads as:
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I am not sure I can really do this in with a single command.
Of course I know how to do it with 2 (query + conditional add).
This is the file:
I would like to add/replace
[{"name": "one", "value": "1"}]
only if the object withname
"one" is not in thelist
, so only a single object is present in the list with the propery"name": "one"
.Any hint?
Beta Was this translation helpful? Give feedback.
All reactions