Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres array of JSON avoid casting

Issuing on PostgresSQL 9.2 the following:

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 error: column "ja" is of type json[] but expression is of type text[]

I can cast type to prevent the error:

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

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

like image 237
rlib Avatar asked Aug 07 '13 09:08

rlib


1 Answers

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

To avoid the confuse escaping cast each string:

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

Or just cast the array itself:

insert into test (ja) values
(array['{"name":"alex", "age":20}', '{"name":"peter", "age":24}']::json[]);
like image 156
Clodoaldo Neto Avatar answered Oct 05 '22 23:10

Clodoaldo Neto