Skip to content
TheChatArchiveThe Chat Archive
Amazon Novaamazon-nova-experimental-chat-05-14· AmazonHugging Face LMArena Human Preference 140K

In postgres, how can I convert json array of integers to postgres int4[]?

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-3-7-sonnet-20250219-thinking-32k’s answer.
  1. User

    In postgres, how can I convert json array of integers to postgres int4[]?

  2. Amazon Nova Assistant

    In PostgreSQL, you can convert a JSON array of integers to a PostgreSQL int4[] (array of integers) using the jsonb_array_elements_text function along with array aggregation. Here's a step-by-step guide on how to achieve this:

    Step-by-Step Conversion

    1. Ensure your JSON is in jsonb format: If your JSON is stored as json, it's better to cast it to jsonb because jsonb has more efficient functions and operators.

    2. Use jsonb_array_elements_text to expand the JSON array: This function expands a JSON array into a set of JSON values.

    3. Cast the text values to integers and aggregate them into an array: Use the ARRAY constructor to aggregate the integer values into an int4[].

    Example

    Assume you have a table my_table with a column json_data that contains a JSON array of integers.

    CREATE TABLE my_table (
        id serial PRIMARY KEY,
        json_data jsonb
    );
    
    INSERT INTO my_table (json_data) VALUES
    ('[1, 2, 3, 4, 5]'::jsonb),
    ('[6, 7, 8, 9, 10]'::jsonb);
    

    To convert the json_data column to an int4[], you can use the following query:

    SELECT 
        id,
        ARRAY(
            SELECT (jsonb_array_elements_text(json_data)::int)
        ) AS int_array
    FROM 
        my_table;
    

    Explanation:

    1. jsonb_array_elements_text(json_data):

      • This function takes the json_data column and expands the JSON array into a set of text elements.
    2. ::int:

      • Each text element is cast to an integer.
    3. ARRAY(...)

      • The SELECT statement inside the ARRAY constructor will return a set of integers which are then aggregated into an int4[].

    Result

    Running the query will produce the following result:

    idint_array
    1{1,2,3,4,5}
    2{6,7,8,9,10}

    As a Function

    If you need to perform this conversion frequently you can create a function:

    CREATE OR REPLACE FUNCTION jsonb_to_int_array(jsonb_data jsonb)
    RETURNS int4[] AS $$
    BEGIN
        RETURN ARRAY(
            SELECT (jsonb_array_elements_text(jsonb_data)::int)
        );
    END;
    $$ LANGUAGE plpgsql IMMUTABLE;
    

    You can then use this function in your queries:

    SELECT 
        id,
        jsonb_to_int_array(json_data) AS int_array
    FROM 
        my_table;
    
    

    This will yield the same result as the inline query.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.