7

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?

1 Answer 1

15
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[]);
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.