Bomaz - 1 year ago 69
Javascript Question

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

2. Set column formatting as JSON, using :json modifier
const data = {escaping: "d\"on't"};
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.