blogccasion

Note to myself regarding JSON

Note to myself regarding JSON

I have been fiddling around with the JSON notation for a project at Google using Douglas Crockford's implementation of a JSON encoder/decoder called json2.js. JSON is at an interesting point in its life since its "invention". It is widely used, browsers can interpret it with eval('(' + jsonString + ')');. Firefox 2 kind of supports JSON encoding with Object.toSource(); which is not supported on other browsers, though. Firefox 3 ships with a native JSON implementation (see John Resig's blog entry on the state of JSON for more details). One of the problems this situation brings along is the general dilemma with whether it is a good idea or not to extend the prototypes of objects in JavaScript. Think of an extension like Object.prototype.toJSON. If one day browser vendors would ship with a native JSON implementation using the same name, users would be forced to live with the overridden version, a "slow" pure JavaScript implementation, rather than a "fast" native implementation. Douglas Crockford chose this approach in the first place (json.js). It has been fixed with a global JSON object in the current release json2.js.

JSON is not forgiving
Is this correct JSON?
{
  'name': 'Lena',
  'location': 'Hamburg'
}

It is correct object literal notation in JavaScript, but not correct JSON. The difference is minimal, but makes JSON parsers like the above json2.js fail. The correct form is
{
  "name": "Lena",
  "location": "Hamburg"
}

Note the quotes ["] that must be used (and not single apostrophes [']). Good to have picky tools like JSONLint. If you use JSON, and if you experience strange errors, then lint your JSON, and most likely you will bang your head against a wall afterwards.