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
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} .
JSONB and IndexesPostgreSQL can use indexes for the text results as compare operands. GIN index can be used by the GIN JSONB operator class.
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.
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.
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)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With