PostgreSQL json_build_array() Function

The PostgreSQL json_build_array() function creates and returns a JSON array of possibly heterogeneous types from a variadic parameter list.

This function is similar to the jsonb_build_array() function.

json_build_array() Syntax

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

json_build_array(VARIADIC any_value) -> JSON

Parameters

any_value

Required. it is a variadic parameter list. You can pass in any number of parameters of any type.

Return value

The PostgreSQL json_build_array() function returns a possibly heterogeneous JSON array whose arguments are converted from a variadic parameter list.

The json_build_array() function evaluates each parameter in the variadic parameter list, and then uses to_json() to convert each parameter to a JSON value and put it into the final returned array.

json_build_array() Examples

This example shows how to use the PostgreSQL json_build_array() function to build a JSON array.

SELECT json_build_array(1, 'a', true, row(2, 'b', false));
               json_build_array
----------------------------------------------
 [1, "a", true, {"f1":2,"f2":"b","f3":false}]

Here, we used 4 parameters in the function: 1, 'a', true, row(2, 'b', false).

First, the json_build_array() function converts each parameter to a JSON value according to to_json() as follows:

  • to_json(1) returns 1
  • to_json('a'::text) returns "a"
  • to_json(true) returns true
  • to_json(row(2, 'b', false)) returns {"f1":2,"f2":"b","f3":false}

Then, the json_build_array() function assembles the above values into a JSON array [1, "a", true, {"f1":2,"f2":"b","f3":false}] and returns it.