Paddy Paddy - 3 months ago 12
Ajax Question

JSON stringfy call in ajax, that is compatable with ie 6

I wanted to use jQuery's

$.each()
and it works, but not in IE6. So enter json2. So I am getting the data and binding it to a var using

var theData = JSON.stringify(data);


Then calling through an array

var i;
for(i=0; i<theData.Event.Football.length; i++)
{
alert(theData.Event.Football[i].time);
}


Although its just saying "Cannot read property 'Football' of undefined"

Here is the JSON, after 6 hours of trying variations, i am use im just misunderstanding something simple.

{
"Event":{
"Football":[
{
"title": "Some Event",
"time": "6:00" ,
"competitors": {
"competitors1": "Boaty Mc Boat",
"competitors2": "Disco Dave"
},
"win": {
"win1": 1.3,
"win2": 1.89,
"win3": 1.79
}
}, {
"title": "Some Event",
"time": "7:00" ,
"competitors": {
"competitors1": "Flesh Wound",
"competitors2": "None Shall Pass"
},
"win": {
"win1": 2.03,
"win2": 1.79,
"win3": 1.79
}
]
}
}


Final Fix, there was a problem with the AJAX syntax, here is the working version that allows the above code to work

$.ajax({
type: 'GET',
url: "football1.json",
dataType: "json",
processData: true,
contentType: "text/json; charset=utf-8",
data: {},
success: function(data){
alert('working');
// do stuff
},
error: function(jqXHR, textStatus, errorThrown) {
console.debug(textStatus, errorThrown);
}
});

Answer

This line:

var theData = JSON.stringify(data);

takes a data structure and turns it into a string (JSON).

If data is already not a string, just use it directly.

If data is a string and you want to go the other way, you want

var theData = JSON.parse(data);

...where, again, data is a string containing JSON.

At which point, either $.each or your for loop (or your various other options, modulo IE6 (!) support) will loop through theData.Event.Football.