Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I enter JSON value to my postgresql database?

So, I can email address, password and date using this code in node

client.query("INSERT INTO manlalaro (emailaddr,pwd,premiumexpiry) values ('[email protected]','123absurdcodes', DATE '2009-09-19') ",(err,res)=>{
   console.log(err, res)
   client.end()
})

But how do I enter JSON data type successfully without getting errors? I have playersaved which is a data type JSON. enter image description here

like image 865
Aedric Avatar asked Sep 17 '25 00:09

Aedric


1 Answers

The best way to pass the data to be inserted in a separated parameter where the library or the driver do the right treatment to each data type.

In most cases it will be something like this:

client.query("INSERT INTO x (a, b, c) VALUES (?, ?, ?)", [1, "text", { "json": "data" }]);

Or this:

client.query("INSERT INTO x (a, b, c) VALUES ($1, $2, $3)", [1, "text", { "json": "data" }]);

The way to know the right thing to do is read the documentation of the library.

If you are using pg (node-postgres) https://node-postgres.com/

Note: As @Aedric pointed out, in some cases your object must be previously "stringified" (JSON.stringify()). But node-postgres claims it do this automatically. (https://node-postgres.com/features/types#uuid%20+%20json%20/%20jsonb).

like image 77
JDuwe Avatar answered Sep 18 '25 14:09

JDuwe