Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

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?

like image 566
James Avatar asked Mar 12 '14 03:03

James


People also ask

Are backslashes allowed in JSON?

The backslash ( \ ) is a special character in both PHP and JSON. Both languages use it to escape special characters in strings and in order to represent a backslash correctly in strings you have to prepend another backslash to it, both in PHP and JSON.

What happens when you JSON Stringify a string?

The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Does JSON Stringify escape quotes?

JSON. stringify does not act like an "identity" function when called on data that has already been converted to JSON. By design, it will escape quote marks, backslashes, etc. You need to call JSON.


1 Answers

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.

like image 192
Michael Richardson Avatar answered Oct 25 '22 20:10

Michael Richardson