PostgreSQL jsonb_build_object() Function
The PostgreSQL jsonb_build_object()
function creates and returns a JSONB object from a variadic parameter list consisting of alternating keys and values.
This function is similar to the json_build_object()
function.
jsonb_build_object()
Syntax
This is the syntax of the PostgreSQL jsonb_build_object()
function:
jsonb_build_object(VARIADIC any_value) -> JSONB
Parameters
any_value
-
Required. is a variable parameter list. You can pass in any number of parameters of any type. By convention, parameters consist of alternating keys and values. You must provide an even number of arguments.
Return value
The PostgreSQL jsonb_build_object()
function returns a JSONB object constructed from a variadic parameter list consisting of alternating keys and values.
The jsonb_build_object()
function evaluates each parameter in the variable parameter list, where arguments as keys are coerced to text, and arguments as values are to_jsonb()
converted to JSONB values as per .
PostgreSQL will give an error if the number of arguments in the variable parameter list is not even.
jsonb_build_object()
Examples
This example shows how to use the PostgreSQL jsonb_build_object()
function to build a JSONB object.
SELECT jsonb_build_object(1, 'a', true, row(2, 'b', false));
jsonb_build_object
-------------------------------------------------------
{"1": "a", "true": {"f1": 2, "f2": "b", "f3": false}}
Here, we used 4 parameters in the function: 1
, 'a'
, true
, row(2, 'b', false)
. where 1
and true
are the keys and 'a'
and row(2, 'b', false)
are the values.
First, the jsonb_build_object()
function converts each parameter:
1
is the key, which is converted to"1"
'a'
is1
the value of , which is converted to"a"
true
is the key, which is converted to"true"
row(2, 'b', false)
istrue
the value of , which is converted to{"f1":2,"f2":"b","f3":false}}
Then, the jsonb_build_object()
function returns a JSONB object consisting of all the key values: {"1" : "a", "true" : {"f1":2,"f2":"b","f3":false}}
.