How do I retain backslashes in strings when using JSON.stringify?

后端 未结 3 2330
忘掉有多难
忘掉有多难 2021-02-20 16:15

So I got a string that has a backslash in it. \"kIurhgFBOzDW5il89\\/lB1ZQnmmY=\".

I tried adding an extra \'\\\', but JSON.stringify( \"kIurhgFBOzDW5i

相关标签:
3条回答
  • 2021-02-20 16:49
    JSON.parse(JSON.stringify("kIurhgFBOzDW5il89\\/lB1ZQnmmY="))
    // "kIurhgFBOzDW5il89\/lB1ZQnmmY="
    
    0 讨论(0)
  • 2021-02-20 16:51

    JSON.stringify doesn't remove the backslash, it encodes it. When you use JSON.parse on the other end, or whatever you do to decode your JSON, it will return the original string.

    0 讨论(0)
  • 2021-02-20 16:56

    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.

    0 讨论(0)
提交回复
热议问题