Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql - update or delete a value from a nested jsonb element

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

like image 350
LiorH Avatar asked Jul 05 '17 16:07

LiorH


People also ask

How do you update objects in Jsonb arrays with PostgreSQL?

Postgres offers a jsonb_set function for updating JSON fields. The second parameter path defines, which property you want to update. To update items in an array, you can use an index-based approach. To update the first entry in the items array in the example above, a path woud look like this: {items, 0, customerId} .

Can you index Jsonb Postgres?

JSONB and IndexesPostgreSQL can use indexes for the text results as compare operands. GIN index can be used by the GIN JSONB operator class.

Is Postgres Jsonb fast?

Speed. Because JSONB stores data in a binary format, queries process significantly faster. Storing data in binary form allows Postgres to access a particular JSON key-value pair without reading the entire JSON record.

What is the difference between JSON and Jsonb in Postgres?

The json data type stores an exact copy of the input text, which processing functions must reparse on each execution; while jsonb data is stored in a decomposed binary format that makes it slightly slower to input due to added conversion overhead, but significantly faster to process, since no reparsing is needed.


1 Answers

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)
like image 193
Marth Avatar answered Oct 26 '22 23:10

Marth