我有一个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中实现这一目标?
答案 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":"XXXXXXXXXX-XXXXC-XXXX-XXXX-XXXXXXX", "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>