Search code examples
javascriptjsontitanium

JSON deserialize with Javascript - Titanium Appcelerator


I'm calling with Titanium an api that is answering with a JSON that is formatted like this:

{
 "1":{"id":"4","field1":"Name 1","ordering":"1"},
 "2":{"id":"6","field1":"Name 2","ordering":"2"},
 "3":{"id":"7","field1":"Name 3","ordering":"3"},
 "4":{"id":"5","field1":"Name 4","ordering":"4"}
}

I would like to iterate this answer, with a code like this:

json = JSON.parse(this.responseText);
for (var i=0; i<json.length; i++) {
          //Something here with json[i];
          }

This code is not executed as json.length is not a valid value.

How can I solve, without changing server side the JSON?


Solution

  • Use a for in loop to loop over every property in the object:

    for (var i in json)