user3601578
user3601578

Reputation: 1362

insert json array into postgres json []

How to insert the array ["a","b","c"] into test?

create table test( f json [] );

I tried

insert into test (f) values('{\"a\",\"b\",\"c\"}');

but then the escape backslashes are displayed when I select it. Without escaping it does not work at all. (Token "a" is invalid)

select * from test;

f
----
{"\"a\"","\"b\"","\"c\""}

Upvotes: 3

Views: 8210

Answers (1)

Clodoaldo Neto
Clodoaldo Neto

Reputation: 125204

I suppose you just want to insert a json array (json) and not an array of json (json[]):

create table test (f json);
insert into test (f) values(to_json(array['a','b','c']));
select * from test;
       f       
---------------
 ["a","b","c"]

In case you want an array of json:

create table test (f json[]);
insert into test (f) values
    (array[to_json('a'::text),to_json('b'::text),to_json('c'::text)]);
select * from test;
             f             
---------------------------
 {"\"a\"","\"b\"","\"c\""}

Upvotes: 5

Related Questions