JSONB
5 methodsFunctions and operators for the binary JSON type.
jsonb_set(target jsonb, path text[], new_value jsonb, create_missing bool = true) -> jsonbReturns target with the field at the given path set to new_value, optionally creating it.
Parameters
| Name | Type | Description |
|---|---|---|
| target | jsonb | Source JSON document. |
| path | text[] | Array of keys/indices to the target field. |
| new_value | jsonb | Replacement value. |
| create_missing | bool | If true, creates missing keys. |
Returns
jsonb
Example
postgresql
UPDATE profile
SET data = jsonb_set(data, '{address,city}', '"Berlin"', true)
WHERE id = 1;jsonb_build_object(key text, value any, ...) -> jsonbBuilds a JSON object from alternating key/value arguments.
Parameters
| Name | Type | Description |
|---|---|---|
| key | text | Object key. |
| value | any | Value converted to JSON. |
Returns
jsonb
Example
postgresql
SELECT jsonb_build_object('id', id, 'name', name, 'admin', is_admin) FROM users;jsonb @> jsonb -> boolReturns true if the left JSON value contains the right value (top-level containment).
Parameters
| Name | Type | Description |
|---|---|---|
| left | jsonb | Container document. |
| right | jsonb | Contained document. |
Returns
bool
Example
postgresql
SELECT * FROM items WHERE tags @> '["sale"]';jsonb ? text -> boolReturns true if the JSON object has the given top-level key, or array contains the string.
Parameters
| Name | Type | Description |
|---|---|---|
| key | text | Key or array element to test. |
Returns
bool
Example
postgresql
SELECT * FROM config WHERE data ? 'feature_x';jsonb_agg(expr ORDER BY ...) -> jsonbAggregates values into a JSON array, optionally ordered.
Parameters
| Name | Type | Description |
|---|---|---|
| expr | any | Expression aggregated per group. |
Returns
jsonb
Example
postgresql
SELECT user_id, jsonb_agg(id ORDER BY created_at) AS order_ids
FROM orders GROUP BY user_id;