How can I insert into a Postgresql JSON array -


the table definition is:

 chat_id serial primary key, last_update timestamp, messages json[]  

and want insert record this:

insert chats (messages) values ('{{"sender":"pablo","body":"they on us"}}'); 

with error:

error: malformed array literal: "{{"sender":"pablo","body":"they on us"}}" line 1: insert chats (messages) values ('{{"sender":"pablo","bo...

i have tried approach :

insert chats (messages) values (array('{"sender":"pablo","body":"they on us"}')); 

note updating row , inserting array_append works ok.

i think clash between json notation starts { , short hand array notation in postgres string representation of array also denoted {.

the following works:

insert chats    (messages)  values    (array['{"sender":"pablo","body":"they on us"}']::json[]); 

this avoids ambiguity of {{ using explicit array constructor.

to make array json array need either cast string json or resulting array json[] (see example above). casting whole array makes easier if have more 1 json document in row:

insert chats    (messages)  values    (array['{"sender":"pablo","body":"they on us"}',            {"sender":"arthur"}']::json[]); 

alternatively:

insert chats    (messages)  values    (array['{"sender":"pablo","body":"they on us"}'::json,            {"sender":"arthur"}'::json]); 

Comments