0

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?

1
  • 1
    "Every JSON serialization utility or library I've used is seems to be broken..." The fact that it's every one of them should suggest to you that your understanding may be incomplete, as opposed to everyone else getting it wrong. :-) Commented Nov 2, 2012 at 15:01

1 Answer 1

3

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.parse is 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.