kevinhakanson.com

JavaScript vs. JSON encoding

August 3, 2009 #javascript

In the process of converting some JavaScript code which creates an object from a JSON string from using (the evil) eval to using JSON.parse (which is native in IE8 and Firefox 3.5), a strange bug was encountered.  Take the following JavaScript snippet, which can be validated using JSLint.

var x = { "name" : "Kevin\\'s Folder" };

However, if you take { "name" : "Kevin\\'s Folder" } and try and validate with JSONLint, it fails parsing.  Why is that?  Look at the definition for string at JSON.org, and you see that it’s not valid to escape the single quote character.  This appears to be because only double quotes are a valid wrapper for a string in JSON, where either single quotes or double quotes are allowed for JavaScript strings.  The JavaScript escape utility used wouldn’t know how the consumer would wrap the string, so it played it safe and escaped both.

The moral of this story?  JSON is a proper subset of pure JavaScript object literals.


Kevin Hakanson

Multi-Cloud Certified Architect | DevSecOps | AppSec | Web Platform | Speaker | Learner | Builder
Twitter | LinkedIn | GitHub | Stack Overflow | Credly

© 2024 Kevin Hakanson (built with Gatsby)