简体   繁体   English

转义JSON以避免更改插入字符串

[英]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: 我有以下json字符串,应将其直接插入到数据库中的单个列中:

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? 删除d中的转义\\并使字符串无效json。有什么方法可以避免这种情况?

This would be beneficial since it would be nice if my valid json would remain so. 这将是有益的,因为如果我保持有效的json会很好。

  1. Don't stringify your data into JSON, use it directly 不要将数据字符串化为JSON,直接使用
  2. Set column formatting as JSON, using :json modifier 使用:json修饰符将列格式设置为JSON

 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. 但是,如果您的data始终是一个对象,那么您甚至不需要使用:json修饰符,它将自动格式化为正确的JSON。

For more details see the flexibility of the ColumnSet type. 有关更多详细信息,请参见ColumnSet类型的灵活性。 You can manipulate your input data in every thinkable way. 您可以通过各种可行的方式来处理输入数据。

This string in js const jsString = JSON.stringify({"escaping":"d\\\\\\"on't"}); will result in this {"escaping":"d\\\\\\"on't"} js const jsString = JSON.stringify({"escaping":"d\\\\\\"on't"});字符串将导致此{"escaping":"d\\\\\\"on't"}

While this string in js const jsString = JSON.stringify({"escaping":"don't"}); 虽然此字符串在js const jsString = JSON.stringify({"escaping":"don't"}); will result in this {"escaping":"don't"} 将导致此{"escaping":"don't"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM