Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I JSON.stringify(object) I get a crazy string as a value

When I send an object with an array of objects in it from my express route to my client, I get an [Object object] and then when I try to stringify it, I get this crazy string with this console message

var messages = "<%=(JSON.stringify(messages))%>"
console.log(messages) 

Which prints this out to the console ...

{&#34;messages&#34;:[{&#34;content&#34;:&#34;cool mane&#34;,&#34;creator&#34;:&#34;joe&#34;},{&#34;content&#34;:&#34;test 4&#34;,&#34;creator&#34;:&#34;joe&#34;},{&#34;content&#34;:&#34; ewgdqf&#34;,&#34;creator&#34;:&#34;joe&#34;},

It should be something so I can iterate through it by doing messages[0].content but I'm getting this crazy string that won't let me do anything with it...

If I try to loop through it, it just prints out each character by itself.

like image 321
joe Avatar asked May 09 '16 16:05

joe


People also ask

What happens when you JSON Stringify a string?

JSON.stringify() converts a value to JSON notation representing it: Boolean , Number , String , and BigInt (obtainable via Object() ) objects are converted to the corresponding primitive values during stringification, in accordance with the traditional conversion semantics.

What is the output of JSON Stringify?

Stringify a JavaScript Object const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

Does JSON Stringify work on objects?

JSON. stringify() will encode values that JSON supports. Objects with values that can be objects, arrays, strings, numbers and booleans. Anything else will be ignored or throw errors.

Why JSON Stringify does not work on array?

The JSON array data type cannot have named keys on an array. When you pass a JavaScript array to JSON. stringify the named properties will be ignored. If you want named properties, use an Object, not an Array.


1 Answers

When using <%= ... %>, EJS will encode / escape any output. That's why the " in the JSON are encoded as &#34;. According to this answer, you can prevent escaping by using <%- ... %> instead.

There is also no need to put the output inside a string literal. It's actually bad since you can get problems with nested quotes. Just let it output directly into the JS code:

var messages = <%-JSON.stringify(messages)%>;
like image 81
Felix Kling Avatar answered Oct 01 '22 14:10

Felix Kling