HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

how to add a new property in jsonb field type?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
fieldnewtypepropertyhowjsonbadd

Problem

I have a jsonb field type named "attributes" in my table, it contains like below:

"attributes"
{
"pid": 5,
"extras": {
"option1": true,
"option2": false
}
}


how to add a new property called option3 with value false?

{ 
  "pid": 5,
  "extras": {
   ...,
   ...,
   "option3": false
   }
}

Solution

The Postgres Online Documentation is the best resource for learning more about JSONB operators. (Make sure you select the version you are using in the upper left if you are not on the current version, 13 as of this writing.)

You can use the jsonb_set function, e.g.

UPDATE demo
SET attributes = jsonb_set(attributes, '{extras,option3}','false', true /* create the field if missing */)
WHERE attributes->>'pid' = '5';


See a working example here.

Code Snippets

UPDATE demo
SET attributes = jsonb_set(attributes, '{extras,option3}','false', true /* create the field if missing */)
WHERE attributes->>'pid' = '5';

Context

StackExchange Database Administrators Q#299740, answer score: 3

Revisions (0)

No revisions yet.