Bomaz Bomaz - 2 years ago 110
JSON Question

Escaping values to avoid changing the string inserted

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:


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.

Answer Source
  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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download