Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I insert into a Postgresql JSON array

The table definition is:

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

and I want to insert a record like this:

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

with error:

ERROR: malformed array literal: "{{"sender":"pablo","body":"they are on to us"}}" LINE 1: insert into chats (messages) values ('{{"sender":"pablo","bo...

I have also tried this approach :

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

Note that updating the row and inserting with array_append works OK.

like image 977
arisalexis Avatar asked Jan 29 '16 10:01

arisalexis


People also ask

Can we insert JSON data into PostgreSQL?

Some of the popular Operators useful for inserting JSON into PostgreSQL are: -> Operator: It enables you to select an element from your table based on its name. Moreover, you can even select an element from an array using this operator based on its index.

Can you insert array in PostgreSQL?

PostgreSQL allows columns of a table to be defined as variable-length multidimensional arrays. Arrays of any built-in or user-defined base type, enum type, composite type, range type, or domain can be created.

How do you update objects in Jsonb arrays with PostgreSQL?

Postgres offers a jsonb_set function for updating JSON fields. The second parameter path defines, which property you want to update. To update items in an array, you can use an index-based approach. To update the first entry in the items array in the example above, a path woud look like this: {items, 0, customerId} .


1 Answers

I think this is a clash between the JSON notation that starts with { and the short hand array notation in Postgres where the string representation of an array is also denoted by an {.

The following works:

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

This avoids the ambiguity of the {{ by using an explicit array constructor.

To make the array a json array you need to either cast the string to a json or the resulting array to a json[] (see the example above). Casting the whole array makes it easier if you have more than one JSON document in that row:

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

alternatively:

insert into chats 
  (messages) 
values 
  (array['{"sender":"pablo","body":"they are on to us"}'::json, 
         '{"sender":"arthur"}'::json]);
like image 135
a_horse_with_no_name Avatar answered Oct 04 '22 20:10

a_horse_with_no_name