views:

63

answers:

3

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 existence 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.

A: 

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.

joni
+5  A: 

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.

VoteyDisciple
+1  A: 

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.

LarsH