DrKey
DrKey

Reputation: 3495

JSON.stringify - Strange behaviour with backslash in array

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?

Upvotes: 1

Views: 4895

Answers (1)

philz
philz

Reputation: 1022

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")

Upvotes: 3

Related Questions