假设我有这个简单的JSON:
现在我想将其转换为以下格式:
{"test":"test"}
现在我想将其转换为以下格式:
{\"test\":\"test\"}
我发现了一些替换双引号为反斜杠和双引号的解决方案,但这些都是针对文本格式的。
我需要将这种格式作为消息参数传递给AWS SNS。
{"test":"test"}
{\"test\":\"test\"}
我发现了一些替换双引号为反斜杠和双引号的解决方案,但这些都是针对文本格式的。
我需要将这种格式作为消息参数传递给AWS SNS。
您可以使用JSON.stringify()将JSON对象首先转换为字符串格式。
var temp = {"test":"test"};
var tempStr = JSON.stringify(temp);
console.log(tempStr); //> {"test":"test"}
var modifiedStr = tempStr.replace(/"/g, '\\"');
console.log(modifiedStr); //> {\"test\":\"test\"}
如果您只想编码开放和关闭双引号,可以尝试以下方法
var temp = {"test":'te"st'};
var tempObj = JSON.parse(JSON.stringify(temp));
for(var k in tempObj){
tempObj[k]=tempObj[k].replace(/"/g, "<DOUBLE_QUOTES_4594>");
}
var tempStr = JSON.stringify(tempObj);
console.log(tempStr); //> {"test":"te<DOUBLE_QUOTES_4594>st"}
var modifiedStr = tempStr.replace(/"|"/g, '\\"').replace(/<DOUBLE_QUOTES_4594>/g, '"');
console.log(modifiedStr); //> {\"test\":\"te"st\"}
如我在评论中提到的那样,您可以使用 JSON.stringify
两次将 Javascript object
转换为 escaped JSON
var myObject = {"test":"test"};
var myJson = JSON.stringify(myObject); // {"test":"test"}
var myEscapedJson = JSON.stringify(myJson); // "{\"test\":\"test\"}"