1

I was playing with JS while I noticed a strange behaviour with backslash \ inserted into a string within an array printed using JSON.stringify(). Of course the backslash is used to escaping special chars, but what happens if we need to put backslash in a string? Just use backslash to escape itself you're thinking, but it doesn't work with JSON.stringify

This should print one backslash

array = ['\\'];
document.write(JSON.stringify(array));

This should print two backslashes

array = ['\\\\'];
document.write(JSON.stringify(array));

Am I missing something? Could be that considered as a bug of JSON.stringify?

4
  • JSON.stringify is escaping the backslashes you already have. Commented Apr 14, 2015 at 23:51
  • 1
    "This should print one backslash" --- it should not Commented Apr 14, 2015 at 23:52
  • So how can I print a single backslash with JSON.stringify? Of course array = ['\']; will fail with an unterminated string.. Commented Apr 14, 2015 at 23:53
  • 2
    The backslash is also the escape character in JSON. See json.org, string. "\" would be invalid JSON, since it is an unterminated string. I'm not sure where your confusing comes from. Commented Apr 15, 2015 at 0:04

1 Answer 1

3

It is correct. JSON.stringify will return the required string to recreate that object - as your string requires that you escape a backslash, it will also return the required escape backslash to generate the string properly.

Try this:

array = ['\\'];
var x = JSON.stringify(array)
var y = JSON.parse(x)
if (array[0] == y[0]) alert("it works")

or

array = ['\\'];
if (JSON.parse(JSON.stringify(array))[0] == array[0]) alert("it really works")
Sign up to request clarification or add additional context in comments.

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.