14

So I got a string that has a backslash in it. "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?

2
  • 1
    Why you need JSON.stringify a string? Commented Mar 12, 2014 at 3:47
  • @xdazz it's part of a larger object which is sent to the server Commented Mar 12, 2014 at 4:17

3 Answers 3

12

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The backslash is actually lost in this example. JSON.stringify( { "a": "^sports\..*" } ) {"a":"^sports..*"} JSON.parse( '{"a":"^sports..*"}' ); Object {a: "^sports..*"}
The backslash is not lost due to JSON.stringify() or JSON.parse(); it is lost because the literal is not well-formed. In other words, "^sports\..*" === "^sports..*" is true.
3

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.

3 Comments

You're 2nd example is incorrect though. JSON.stringify("\\/") returns "\\/" not "\/"
@jk7 maybe my wording was unclear. I'm not saying the result of stringifying "\\/" is "\/", I'm saying the result of parsing the stringified string is "\/", ie JSON.parse(JSON.stringify("\/")) > "/" and JSON.parse(JSON.stringify("\\/")) > "\/"
yes, that's true. The problem some of us have is that the stringified string is not going to be parsed by JSON.parse() but rather by server logic and needs to be sent as "\/" instead of "/". Example: "\/Date(1502450577171+0000)\/"
0
JSON.parse(JSON.stringify("kIurhgFBOzDW5il89\\/lB1ZQnmmY="))
// "kIurhgFBOzDW5il89\/lB1ZQnmmY="

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.