Every JSON serialization utility or library I’ve used is seems to be broken, and I cannot get the logical explanation on this.
Let me explain. I run following code in Firebug for JSON libraries for .NET, probably for other languages.
I just check in Firefox, when I run:
var obj1 = "test";
var obj1serialization = JSON.stringify(obj1);
The output is ""test"". But this is invalid JSON object! So when I tried to re-create object from that serialized JSON, it failed, stating that JSON string is incorrect:
var obj2 = JSON.parse(obj1serialization);
Strings are objects. But their serialization in JSON not working. Is there any logical explanation of this situation?
In JSON (unlike several programming languages), strings are not objects, they’re primitives (like numbers and booleans). You’re asking the serializer to create a JSON fragment. A valid JSON document’s top-level item is always an object or an array. If you feed one of those into
JSON.stringify, it will produce a valid, complete JSON document.The fact that most JSON serializers allow fragments is quite useful. The only alternative they’d have would be to throw an exception if you passed something into them that wasn’t an object or array.
JSON.parseis more restrictive, requiring that the JSON document you give it be both complete and well-formed. Not all JSON parsing routines are that restrictive, but that one is.