使用 JSON.stringify 时如何在字符串中保留反斜杠?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22341571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I retain backslashes in strings when using JSON.stringify?
提问by James
So I got a string that has a backslash in it. "kIurhgFBOzDW5il89\/lB1ZQnmmY=".
所以我得到了一个带有反斜杠的字符串。"kIurhgFBOzDW5il89\/lB1ZQnmmY=".
I tried adding an extra '\', but JSON.stringify( "kIurhgFBOzDW5il89\\/lB1ZQnmmY=")returns the string with two backslashes instead of one. Is there any way to keep the backslash using JSON.stringify?
我尝试添加一个额外的“\”,但JSON.stringify( "kIurhgFBOzDW5il89\\/lB1ZQnmmY=")返回带有两个反斜杠而不是一个的字符串。有没有办法使用 JSON.stringify 保留反斜杠?
采纳答案by Michael Richardson
JSON.stringifydoesn't remove the backslash, it encodes it. When you use JSON.parseon the other end, or whatever you do to decode your JSON, it will return the original string.
JSON.stringify不会删除反斜杠,而是对其进行编码。当您JSON.parse在另一端使用时,或者无论您做什么来解码您的 JSON,它都会返回原始字符串。
回答by chiliNUT
The backslash is escaping the forward slash. So JSON.stringify("\/")returns "/"since it sees an escaped forward slash, so its just a forward slash. JSON.stringify("\\/") sees a backslash being escaped, and then a forward slash next to that, so it returns "\/". You cannot preserve the "exact" string when you stringify, since parsing a json string will not escape characters, so you get back your original data, just unescaped.
反斜杠正在逃避正斜杠。所以JSON.stringify("\/")返回,"/"因为它看到一个转义的正斜杠,所以它只是一个正斜杠。JSON.stringify("\\/") 看到一个反斜杠被转义,然后在它旁边有一个正斜杠,所以它返回"\/"。字符串化时您无法保留“精确”字符串,因为解析 json 字符串不会转义字符,因此您会取回原始数据,只是未转义。
回答by cbayram
JSON.parse(JSON.stringify("kIurhgFBOzDW5il89\/lB1ZQnmmY="))
// "kIurhgFBOzDW5il89\/lB1ZQnmmY="

