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[]);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply, especially the second form.
can you please answer this stackoverflow.com/questions/51571453/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.