PostgreSQL json_build_object() Function

The PostgreSQL json_build_object() function creates and returns a JSON object from a variadic parameter list consisting of alternating keys and values.

This function is similar to the jsonb_build_object() function.

json_build_object() Syntax

This is the syntax of the PostgreSQL json_build_object() function:

json_build_object(variadic any_value) -> JSON



Required. it is a variadic 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 parameters.

Return value

The PostgreSQL json_build_object() function returns a JSON object constructed from a variadic parameter list consisting of alternating keys and values.

The json_build_object() function evaluates each argument in the variadic parameter list, where parameters as keys are coerced to text, and parameters as values ​​are converted to JSONB values ​​according to to_jsonb().

PostgreSQL will give an error if the number of arguments in the variadic parameter list is not even.

json_build_object() Examples

This example shows how to use the PostgreSQL json_build_object() function to build a JSONB object.

SELECT json_build_object(1, 'a', true, row(2, 'b', false));
 {"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 json_build_object() function converts each parameter as following:

  • 1 is the key, which is converted to "1"
  • 'a' is the value of 1, which is converted to "a"
  • true is the key, which is converted to"true"
  • row(2, 'b', false) is the value of true, which is converted to {"f1":2,"f2":"b","f3":false}}

Then, the json_build_object() function returns a JSONB object consisting of all the key-value pairs: {"1" : "a", "true" : {"f1":2,"f2":"b","f3":false}}.