0

I'm trying to insert a JSON Array (defined as "_json" in the table structure) to a PostgreSQL table, using a csv. This is the insert statement:

INSERT INTO "MySchema".my_table (id, main_array) values(DEFAULT, '{{"KeyA": 10,"KeyB":20},{"KeyA": 100,"KeyB":200}}');

Getting the following error:

ERROR: malformed array literal 
Detail: Unexpected array element.

Note that I generate the INSERT statement from the database itself. The node.js Sequelize code is working fine with JSON array.

Here's the csv file structure:

mytable.csv

1,{{"KeyA": 10,"KeyB":20},{"KeyA": 100,"KeyB":200}}
7
  • See the commas? That's your problem. Commented Sep 9, 2022 at 9:55
  • Can you please elaborate a little more? Commented Sep 9, 2022 at 9:57
  • Your CSV line consists of 5 entries. The first is 1, the second is {{"KeyA": 10, and so on. That second entry is clearly not a valid array. You will have to escape something, because as it is, your CSV is corrupt. Commented Sep 9, 2022 at 10:00
  • I understand that. That's precisely my question. Commented Sep 9, 2022 at 10:24
  • You will have to fix the data. Commented Sep 9, 2022 at 10:53

2 Answers 2

1

The correct INSERT statement is:

INSERT INTO "MySchema".my_table (id, main_array)
values (
   DEFAULT,
   '{"{\"KeyA\": 10,\"KeyB\":20}","{\"KeyA\": 100,\"KeyB\":200}"}'
);

The array elements are enclosed in double quotes and the double quotes in them are escaped with backslashes.

The whole thing would look much simpler if you used a JSON array instead of a PostgreSQL array:

INSERT INTO "MySchema".my_table (id, main_array)
values (
   DEFAULT,
   '[{"KeyA": 10, "KeyB": 20}, {"KeyA": 100, "KeyB": 200}]'
);
Sign up to request clarification or add additional context in comments.

4 Comments

I want the resulting array in DB to be like: [{"KeyA": 10,"KeyB":20}]. And, this format is giving: malformed array literal. "[" must introduce explicitly-specified array dimensions.
Ah, silly me. I missed that the type you are using is json[] rather than json.
Still not working.
Another mistake of mine: You are not loading the CSV file with COPY, you are actually running INSERT.
0

Just another way to escape simiar to Laurenz please let me know if it helps

[  {    \"KeyA\":10,    \"KeyB\":20  },  {  \"KeyA\":100,     \"KeyB\":200   }]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.