PDA

View Full Version : Ext.decode and arrays



profunctional
7 Jul 2010, 7:09 AM
I'm using the following line of code to decode some json data:

var jsonData = Ext.util.JSON.decode(response.responseText);

The data being returned looks something like this {"Rows":[ "RowNum":1", ......

My problem is that when I do jsonData.Rows[0].RowNum, it is telling me that Rows is undefined.

What is the correct way to use the decode method?

tubamanu
7 Jul 2010, 7:20 AM
Using Ext.decode is the right way. It can be something like this



Ext.Ajax.request({
url : 'url.php',
success: function( response) {
var serverResponse = Ext.util.JSON.decode(response.responseText);
alert(serverResponse.test);
}
});



but u need to be sure, that your JSON response from server is valid. With this JSON snippet the failure is hard to find....

evant
7 Jul 2010, 7:21 AM
Well, from the sample you post, it's not valid json.



{
Rows: [RowNum: 1] // <--- not valid
}




{
Rows: [{
RowNum: 1
}]
}

profunctional
7 Jul 2010, 7:25 AM
The documentation says that if the json is invalid, there will be a syntax error thrown. So I know that the json is fine. This same json string works with jquery's jQuery.parseJSON so I'm positive there is no problems with the data.

With jquery i can do this:

var obj = jQuery.parseJSON(json);

$.each(obj.Rows, function(i, ticket)
{
}

But I thought the whole point of moving to sencha was going lightweight, and not having to include jquery.

evant
7 Jul 2010, 7:26 AM
Well, you haven't show what your json is, so I can't really comment definitively. The more info you provide the more likely it is someone can help you.

profunctional
7 Jul 2010, 7:35 AM
Here is the Json string.

{"Rows":[ {"RowNum":"1","TicketId":"33371", "BusinessUnit":"null","Test Field":""}]}

evant
7 Jul 2010, 7:43 AM
Ok, the JSON is valid. What is jsonData? Have you checked if it's null?

For example:



var s = '{"Rows":[ {"RowNum":"1","TicketId":"33371", "BusinessUnit":"null","Test Field":""}]}';
var o = Ext.decode(s);

console.log(o.Rows[0].RowNum);

profunctional
7 Jul 2010, 7:49 AM
jsonData is not null. When I write out the value, it is the json string specified in the previous thread.

profunctional
7 Jul 2010, 7:52 AM
Well, this is strange. calling decode twice like the below works:

var jsonData = Ext.decode(response.responseText);
var s = jsonData;
var o = Ext.decode(s);
alert(o.Rows[5].TicketId);

tubamanu
7 Jul 2010, 7:54 AM
somethin like this dirty code^^ should do it
i just tested it and it works on my dev environment



Ext.Ajax.request({
url : serverURL,
success: function(objServerResponse){
var serverResult = Ext.util.JSON.decode(objServerResponse.responseText);

for (var a = 0; a < serverResult.Rows.length; a++) {
var row = serverResult.Rows[a];
alert(row.TicketId);
}
//alert(serverResult.Rows[0].TicketId);
}
});

profunctional
7 Jul 2010, 8:06 AM
thanks guys.