Bomaz
Bomaz

Reputation: 1961

Escaping JSON to avoid changing the insert string

I have the following json string that should be inserted directly into the database in a single column:

const jsString = JSON.stringify({"escaping":"d\"on't"});

const insertion = [{"a":2,"json":jsString}];

const query = pgp.helpers.insert(insertion,["a","json"],"tbl");

however what actually ends up in the database is:

{"escaping":"d"on't"}

removing the escaping \ in d"on't and making the string invalid json. Is there some way to avoid this?

This would be beneficial since it would be nice if my valid json would remain so.

Upvotes: 1

Views: 252

Answers (2)

vitaly-t
vitaly-t

Reputation: 25840

  1. Don't stringify your data into JSON, use it directly
  2. Set column formatting as JSON, using :json modifier

const data = {escaping: "d\"on't"};
const insertion = [{a:2, json:data}];
const query = pgp.helpers.insert(insertion, ["a", "json:json"], "tbl");

But if your data is always an object, then you don't even need to use the :json modifier, it will be automatically formatted as correct JSON.

For more details see the flexibility of the ColumnSet type. You can manipulate your input data in every thinkable way.

Upvotes: 2

Ronaldo Felipe
Ronaldo Felipe

Reputation: 402

This string in js const jsString = JSON.stringify({"escaping":"d\\\"on't"}); will result in this {"escaping":"d\\\"on't"}

While this string in js const jsString = JSON.stringify({"escaping":"don't"}); will result in this {"escaping":"don't"}

Upvotes: 0

Related Questions