开发者

Parsing JSON with Javascript

I have a webservice (RestEasy) returning a JSON object containing a List<..> element. I am trying to parse the results in a Javascript for loop. If the List<> element has 2 or more elements, all is well. If the List<> element has only one element, the Javascript loop breaks.

This is because the JSON respresentation actually changes when there is only one element. For example:

{"parent":[{"a":1},{"b":2}]}

works just fine ... but for some reason, the JSON looks like this for one child:

{"parent":{"a":1}}

Note ... that the array indicator [] is missing.

Is that standard JSON? This type of notation forces ugly, unnecessary checks in my javascript for existenc开发者_如何学Pythone or size, etc of an expected array ...

Is this consistent standard practice? Why doesn't JSON return a list of one?

{"parent":[{"a":1}]}

Is this possibly an artifact of my server side and would other server side generators actually build a different JSON representation? I even tried to use dojo.forEach and it works great until it reaches the single element array that unfortunalty, lacks any type of list notation.


This has nothing to do with the JSON format. The JSON format absolutely distinguishes between {"a":1} (an object) and [{"a":1}] (an array containing an object as its only element).

Seeing it behave differently is a bug in the server-side generator. You'd have to dig into that code to find out why it would choose to misrepresent single-element arrays.


This is not a problem with JSON per se. JSON is merely a set of lexical rules. Rather, it sounds like a poor design or implementation of the REST web service.

If the specification says it will change the structure based on whether there is one item or several, then I would say it's a surprising design that violates the "principle of least astonishment." If the specification doesn't say this, then it would be a bug in the web service.


This is an artifact of your server side. Might be your framework supplies the datastructure to the JSON generator in this way, I guess it's not the problem of the generator itself.


Whilst not a JS/JSON problem, a JS workaround is available like so:

if(data["parent"]["child"] instanceof Array) {  
    $.each(data["parent"]["child"], function(i, attr) {
         var myVal = attr["@name"];
         //now do something
     });    
}
else {
     var myVal = data["parent"]["child"]["@name"];
     // do something
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜