I'm a beginner to SQL (as you'll soon be able to tell...) and I cannot for the life of me figure out how to best insert a simple JSON array of strings into a PostgreSQL table. I suspect the solution is quite easy but I've spent just a bit too long trying to puzzle it out on my own.
First I create the table:
CREATE TABLE test (
id serial PRIMARY KEY
my_array jsonb
);
Where the array is of type JSON. Insert some initial data:
INSERT INTO test (id, my_array) VALUES(1, '[]');
And now I want to update the myarray
column with a JSON array using Node.js node-postgres. The array might look something like
const myArray = ['foo', 'bar', 'foobar\'s escaped character emporium'];
await db.none(
'UPDATE test ' +
`SET my_array = ${myArray} ` +
'WHERE id = 1'
);
This results in
error: syntax error at or near ","
Ok, so what if I do
await db.none(
'UPDATE test ' +
`SET my_array = "${myArray}" ` +
'WHERE id = 1'
);
I get
error: column "foo,bar,foobar's escaped character emporium" does not exist
and if I do
await db.none(
'UPDATE test ' +
`SET my_array = ${JSON.stringify(myArray)} ` +
'WHERE id = 1'
);
I get
ERROR error: syntax error at or near "["
Finally, if I do
await db.none(
'UPDATE test ' +
`SET my_array = '${JSON.stringify(myArray)}' ` +
'WHERE id = 1'
);
I end up with
stack=error: syntax error at or near "s"
I've also tried storing the data data as a native PostgreSQL array but I encounter similar problems:
CREATE TABLE test (
id serial PRIMARY KEY
my_array text ARRAY
);
INSERT INTO test (id, my_array) VALUES(1, '{}');
Then
const myArray = ['foo', 'bar', 'foobar\'s escaped character emporium'];
await db.none(
'UPDATE test ' +
`SET my_array = ${myArray} ` +
'WHERE id = 1'
);
gives
stack=error: syntax error at or near ","
Similar variations using JSON.stringify()
and combinations of different quotes have proved fruitless as well. I kind of expected this approach to be less likely to work as PostgreSQL arrays are just a different format, but I was hoping there might be some kind of attempt at coercion. Reading through the documentation I can't spot any obvious way to convert a JSON array into the expected format for a PostgreSQL array.