如何生成带有转义字符的json字符串

时间:2017-11-07 08:59:44

标签: javascript json

我有一个json字符串,

{"eID":"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX","cID":"XXXXXXXXXX-XXXXC-XXXX-XXXX-XXXXXXX"}. 

我通过字符串化JSON获得了这个。但我需要JSON文件的格式,其中每个键和值都有转义字符,如

{\"eID\":\"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX\",\"cID\":\"XXXXXXXXXX-XXXXC-XXXX-XXXX-XXXXXXX\"}. 

如何在JavaScript中实现这一目标?

3 个答案:

答案 0 :(得分:2)

你可以再次进行字符串化。



var string = '{"eID":"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX","cID":"XXXXXXXXXX-XXXXC-XXXX-XXXX-XXXXXXX"}';

console.log(JSON.stringify(string));




答案 1 :(得分:-1)

如果您想将替换为 \”,则只需字符串化值上的replace(/"/g, "\\\"")

var obj = {
  "eID": "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX",
  "cID": "XXXXXXXXXX-XXXXC-XXXX-XXXX-XXXXXXX"
};

console.log(JSON.stringify(obj).replace(/"/g, "\\\""));

如果要将此替换更改恢复为JSON值,请使用replace(/\\\"/g, "\"")

<强>演示

var obj = {"eID":"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX","cID":"XXXXXXXX‌​XX-XXXXC-XXXX-XXXX-X‌​XXXXXX", "user": "domain\\username" };
var escapedValue = JSON.stringify( obj ).replace(/"/g, "\\\"")
var oldValue = escapedValue.replace(/\\\"/g, "\"");
console.log( oldValue );

答案 2 :(得分:-1)

您可以使用“JSON.stringify(your_json)”将您的json解析为纯文本。

var json = {"eID":"XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXX","cID":"XXXXXXXXXX-XXXXC-XXXX-XXXX-XXXXXXX"};


document.getElementById('result').innerText = JSON.stringify(json);
<span id="result"></span>