tags:

views:

132

answers:

2

I am playing with the 1.4.1 jquery.parseJSON method and looks like it would be a good fit for my project which is iterating over a JSON string that is loaded from C#. However, the JSON that gets loaded is an entity object and they have generic collections inside of them and thus creates the same name in the JSON string. For example:

This works because theres only item with a name all to itself:

var obj = jQuery.parseJSON('{\"ItemID\":1014470}');
alert(obj.ItemID);

This works but only gets the last item in the JSON string:

var obj = jQuery.parseJSON('{\"ItemID\":1014470,\"ItemID\":134564879898798}');
alert(obj.ItemID);

So I thought separating the JSON string as follows would solve it:

var obj = jQuery.parseJSON('{\"ItemID\":1014470},{\"ItemID\":134564879898798}');

Which of course does nothing

I was thinking that you could do something like this:

jQuery.each(obj, function(){
     // get each ItemID ???
});

Is there a better way to do something like this?

Currently we use these ugly javascript arrays with lots and lots of looping methods, I was hoping jQuery could provide a cleaner way of iterating over a JSON string.

+1  A: 

If you are willing to change the data format, a json structure like the one below will work for you.

[
    {
        "ItemID": 1014470
    },
    {
        "ItemID": 134564879898798
    }
]

It will build an array of objects that each have the ItemID property.

Only getting the last declaration of a property that's defined multiple times in one object is expected behavior, so you will need to use some sort of array.

anq
+3  A: 

To repeat items, you use an array. Either an array of objects:

[{"ItemID":1014470},{"ItemID":134564879898798}]

or an object that has an array as member:

{"ItemID":[1014470,134564879898798]}

The first one you can loop using:

$.each(arr, function(){
  alert(this.ItemID);
});

The second you can loop using:

$.each(obj.ItemID, function(){
  alert(this);
});
Guffa
+1 this is it, the output is (for all intents and purposes) broken and should be fixed. The notation used can't work in an object, the later key will override the former.
Pekka