18

Is there a way to delete/update a nested json key object (not array) for example the following json:

{
  "top": {
    "nested": {
       "leaf": 1
    }
  }  
}

how would I delete/update the leaf element?

I tried

SELECT jsonb '{"top": {"nested": {"leaf" : 1}}' - '{top,nested,leaf}'

but no luck

1 Answer 1

40

You need to use the #- operator, not -:

SELECT jsonb '{"top": {"nested": {"leaf" : 1}}}' #- '{top,nested,leaf}';
┌─────────────────────────┐
│        ?column?         │
├─────────────────────────┤
│ {"top": {"nested": {}}} │
└─────────────────────────┘
(1 row)

From the documentation:

  • - (given a text argument): Delete key/value pair or string element from left operand. Key/value pairs are matched based on their key value.
  • - (given an int argument): Delete the array element with specified index (Negative integers count from the end). Throws an error if top level container is not an array.
  • #-: Delete the field or element with specified path (for JSON arrays, negative integers count from the end)
Sign up to request clarification or add additional context in comments.

2 Comments

How does it know what table to perform that one THOUGH
@ennth: what do you mean? If you had a table t with a jsonb column j you would do SELECT j -# '{to,remove}' FROM t.

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.