In postgres, how can I convert json array of integers to postgres int4[]?
- User
In postgres, how can I convert json array of integers to postgres
int4[]? Assistant
In PostgreSQL, you can convert a JSON array of integers to a PostgreSQL
int4[](array of integers) using thejsonb_array_elements_textfunction along with array aggregation. Here's a step-by-step guide on how to achieve this:Step-by-Step Conversion
-
Ensure your JSON is in
jsonbformat: If your JSON is stored asjson, it's better to cast it tojsonbbecausejsonbhas more efficient functions and operators. -
Use
jsonb_array_elements_textto expand the JSON array: This function expands a JSON array into a set of JSON values. -
Cast the text values to integers and aggregate them into an array: Use the
ARRAYconstructor to aggregate the integer values into anint4[].
Example
Assume you have a table
my_tablewith a columnjson_datathat 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_datacolumn to anint4[], you can use the following query:SELECT id, ARRAY( SELECT (jsonb_array_elements_text(json_data)::int) ) AS int_array FROM my_table;Explanation:
-
jsonb_array_elements_text(json_data):- This function takes the
json_datacolumn and expands the JSON array into a set of text elements.
- This function takes the
-
::int:- Each text element is cast to an integer.
-
ARRAY(...)- The
SELECTstatement inside theARRAYconstructor will return a set of integers which are then aggregated into anint4[].
- The
Result
Running the query will produce the following result:
id int_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.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.