Node.js JavaScript-stringify

mpen picture mpen · Apr 15, 2013 · Viewed 9.1k times · Source

JSON is not a subset of JavaScript. I need my output to be 100% valid JavaScript; it will be evaluated as such -- i.e., JSON.stringify will not (always) work for my needs.

Is there a JavaScript stringifier for Node?

As a bonus, it would be nice if it could stringify objects.

Answer

SvdB picture SvdB · Apr 15, 2013

You can use JSON.stringify and afterwards replace the remaining U+2028 and U+2029 characters. As the article linked states, the characters can only occur in the strings, so we can safely replace them by their escaped versions without worrying about replacing characters where we should not be replacing them:

JSON.stringify('ro\u2028cks').replace(/\u2028/g,'\\u2028').replace(/\u2029/g,'\\u2029')