Aedric
Aedric

Reputation: 95

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

Upvotes: 4

Views: 7799

Answers (2)

JDuwe
JDuwe

Reputation: 702

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).

Upvotes: 2

Zunnurain Badar
Zunnurain Badar

Reputation: 1042

You can insert JSON data in postgresql by converting it into string using JSON.stringify(Object)

`insert into tableName (id,json_data) values(1,'{"test":1}')`

Upvotes: 2

Related Questions