Postgres JSON array avoids casting

The following on PostgresSQL 9.2:

CREATE TABLE test (j JSON, ja JSON[]); INSERT INTO test (j) VALUES('{"name":"Alex", "age":20}' ); -- Works FINE INSERT INTO test (ja) VALUES( ARRAY['{"name":"Alex", "age":20}', '{"name":"Peter", "age":24}'] ); -- Returns ERROR 

The first insert works fine. The second insert returns an error: the column "ja" is of type json [], but the expression is of type text []

I can use type to prevent error:

 INSERT INTO test(ja) VALUES( CAST (ARRAY['{"name":"Alex", "age":20}', '{"name":"Peter", "age":24}'] as JSON[]) ); -- Works FINE 

My question is, is there a way to avoid casting?

+4
source share
1 answer
 insert into test(ja) values ('{"{\"name\":\"alex\", \"age\":20}", "{\"name\":\"peter\", \"age\":24}"}'); 

To avoid confusion when executing each line:

 insert into test(ja) values (array['{"name":"alex", "age":20}'::json, '{"name":"peter", "age":24}'::json]); 

Or just create an array:

 insert into test (ja) values (array['{"name":"alex", "age":20}', '{"name":"peter", "age":24}']::json[]); 
+10
source

Source: https://habr.com/ru/post/1495706/


All Articles