PostgreSQL json_to_record() Function

The PostgreSQL json_to_record() function expands the specified top-level JSON object into a row with the corresponding type defined in the AS clause.

json_to_record() Syntax

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

json_to_record(from_json JSON) -> RECORD

Parameters

from_json

Required. The JSON object to convert.

Return value

The PostgreSQL json_to_record() function returns a value of RECORD type , which is converted from the specified JSON object. The JSON object is converted to a value โ€‹โ€‹of type RECORD according to the json_populate_record() function.

json_to_record() Examples

This example shows how to use the PostgreSQL json_to_record() function to convert a JSON object to a row with a complex type.

SELECT
  *
FROM
  json_to_record(
    '{"name": "Tom", "age": 20, "hobbies": ["sports", "cars"]}'
  ) AS x(name TEXT, age INT, hobbies TEXT[]);
 name | age |    hobbies
------+-----+---------------
 Tom  |  20 | {sports,cars}

Here, we defined the type of row to return in the AS clause : AS x(name TEXT, age INT, hobbies TEXT[]).

You can also use more complex types by combining custom types.

First, let’s create a custom SQL type:

CREATE TYPE address as (country TEXT, city TEXT);

Then convert a complex JSON object into a row:

SELECT
  *
FROM
  json_to_record(
    '{"name": "Tom", "age": 20, "hobbies": ["sports", "cars"], "address": {"country": "CN", "city": "BeiJing"}}'
  ) AS x(name TEXT, age INT, hobbies TEXT[], address address);
 name | age |    hobbies    |   address
------+-----+---------------+--------------
 Tom  |  20 | {sports,cars} | (CN,BeiJing)

Here, we defined the column address with the type address.