Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify doesn't escape?

I'm using `JSON.stringify? to stringify an object, but the quotes are not escaped? Am I misunderstanding that it's suppose to escape the quotes?

This is outputted into the template without any of the quotes being escaped:

{"console":{"free":false}} 
like image 458
Harry Avatar asked Mar 31 '11 20:03

Harry


People also ask

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.

How do you escape a JSON string?

The only difference between Java strings and Json strings is that in Json, forward-slash (/) is escaped.

What is Stringify in JavaScript?

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.

What is JSON Stringify and JSON parse?

parse() is used for parsing data that was received as JSON; it deserializes a JSON string into a JavaScript object. JSON. stringify() on the other hand is used to create a JSON string out of an object or array; it serializes a JavaScript object into a JSON string. Follow this answer to receive notifications.


2 Answers

stringify the object twice does the trick

console.log(JSON.stringify(JSON.stringify({"console":{"free":false}}))); // "{\"console\":{\"free\":false}}" 
like image 128
Nerdroid Avatar answered Sep 23 '22 15:09

Nerdroid


It doesn't escape characters, no, there's encodeURIComponent for that, and you can use them together, as in encodeURIComponent(JSON.stringify(obj))

like image 40
Jim Blackler Avatar answered Sep 19 '22 15:09

Jim Blackler