5

Given the following json structure:

{
   "elements": [
      {
         "name": "disregard",
         "value": "me"
      },
      {
         "name": "foo",
         "value": "bar"
      },
      {
         "name": "dont-edit",
         "value": "me"
      }
   ]
}

What would be the appropriate jq query to replace the value of the name: foo element or create/add the element to the array, if it doesn't already exist?

7
  • I removed the elipsis, so it's valid JSON. I hope that's what you meant by mre @oguzismail. If you meant an actual query, well then I wouldn't be asking this question, if I could provide that. :) Commented Oct 4, 2019 at 16:07
  • You should also add an output example Commented Oct 4, 2019 at 17:59
  • 1
    @carlossless, I have edited your input so that it's a valid JSON Commented Oct 4, 2019 at 19:12
  • Carlossness - You're supposed also to show some attempt at a solution (even if it's not in jq). @Dmitry - It's still not valid JSON! Commented Oct 4, 2019 at 19:39
  • @peak, yes, it is, however, you probably don't see it yet, due to awaiting a peer review Commented Oct 4, 2019 at 19:42

1 Answer 1

8

Here is a safe if pedestrian solution:

.elements 
|=  (map(.name) | index("foo")) as $ix
    | if $ix 
      then .[$ix]["value"] = "BAR" 
      else . + [{name: "foo", value: "BAR"}]
      end

You might want to abstract away the "foo" and "BAR" bits:

upsert

# Input is assumed to be an array of {name:_, value:_} objects
def upsert($foo; $bar):
  (map(.name) | index($foo)) as $ix
  | if $ix then .[$ix]["value"] = $bar else . + [{name: $foo, value: $bar}] end;

Usage:

.elements |= upsert("foo"; "BAR")
Sign up to request clarification or add additional context in comments.

2 Comments

This is what I'm looking for. But how to deal with issue if .elements doesn't exists? I would need to create that .elements node if id doesn't exists and add entry to it.
If you also want to cover the case that there is no key named "elements" in the object, then use the form .element |= if . == null then ..... else AS_BEFORE end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.