开发者

json serialization weirdness

I'm using a custom JavaScriptConverter to serialize two objects. One of them is a list of objects and it works just fine; the other one 开发者_开发知识库is a single object. I serialize both and put them in the source code of the page. When I look at them HTML source in a browser, I see that the one that works looks like this:

var Object1 = '[{....}]';

while the one that doesn't work looks like this:

var Object2 = '{...}';

When I run an eval, it doesn't work with Object2. I'm just not seeing why the serialization is different since I'm using the same principal for both; I'm obviously doing something wrong. If you've run into a similar issue or have a suggestion, then please let me know.

Thanks.


You are running into a Javascript parsing ambiguity.

Instead of:

eval(json)

you need:

eval('(' + json + ')')

In Javascript, an open brace can start either an object literal:

{ a: 0, b: 1 }

or a block:

{ var a = 3; f(a); }

However, a block cannot appear in an expression, so adding the parentheses resolves the ambiguity.


Section 12.4 of the spec says:

An ExpressionStatement cannot start with an opening curly brace because that might make it ambiguous with a Block. Also, an ExpressionStatement cannot start with the function keyword because that might make it ambiguous with a FunctionDeclaration.

There are numerous workarounds/solutions discussed here:

  • http://rayfd.wordpress.com/2007/03/28/why-wont-eval-eval-my-json-or-json-object-object-literal/


There is nothing weird. In JSON you have normal objects which are denoted with { ... } and lists of normal objects which are denoted with [{ ... }, { ... }, ...] and . So if your second object is not a list you cannot expect it to be serialized as such. If you wanted your second object to be enclosed with [] you could create a list containing one element which is the second object and then serialize this list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜