JSON.parse cannot return length (==undefined)
Hi, I've searched for this problem a bit now and cannot figure out why it doesnt work.
Running the latest SDK (1.8) with iPhone 5.0.
Im creating a JSON-object from the server with php and json_encode. Here's the json-data which is returned in my app:
{
"1": {
"name": "Fresh"
},
"2": {
"name": "Office"
},
"3": {
"name": "Megamixes"
}
}
And im running this in the app:
var request = Ti.Network.createHTTPClient();
request.open("GET", url);
request.onload = function()
{
var playlists = JSON.parse(this.responseText);
Ti.Info("num playlists: " + playlists.length);
};
If I run "alert(playlists[1]['name']);" I get the name from playlist with the Key 1. Why cant I get the length of the JSON-object?
Need it so I can for-loop all the results..
3 Answers
-
Accepted Answer
Mathew, you are trying to get the length of an Object.
Objects don't have length.
Besides this , using numbers for object keys is not a good practice.You can fix this in 2 ways:
1.the best solution
Make your php to return something like
data = [ {"name":"Fresh"}, {"name":"Office"}, {"name":"Megamixes"} ]
then you will have
var playlists = JSON.parse(this.responseText); alert(playlist.data.length);
2.The not so good way
Keep the current structure but loop the object using the for…in loop. This is not goos because is slow so you better modify the server's reply.
var playlists = JSON.parse(this.responseText); for (k in playlist) { Ti.API.info( playlist[k].name); }
-
The JSON is not an array, so you cant get .length, try this format:
{ [ "1": { "name": "Fresh" } ], [ "2": { "name": "Office" } ], [ "3": { "name": "Megamixes" } ] }
-
playlists.length()