Javascript – How to read JSON(server response) in Javascript

appceleratorjavascriptjsonparsing

I am sending some request on a server and it's reply me this:

{"COLUMNS":["REGISTRATION_DT","USERNAME","PASSWORD","FNAME","LNAME","EMAIL","MOBILE","FACEBOOK_ID"],"DATA":[["March, 17 2012 16:18:00","someuser",somepass,"somename","somesur","someemail",sometel,"someid"]]}

I tried a lot but nothing seems to working for me!

var xml2 = this.responseData;
var xml3 = xml2.getElementsByTagName("data");
Ti.API.log(xml3.FNAME);

For this code I get "null".

Any help would be appreciated!

Best Solution

If you're trying to use JSON format, your problem is that the data within the [...] also needs to be in pairs, and grouped in {...} like here.

For instance,

{ 
      "sales": [ 
         { "firstname" : "John", "lastname" : "Brown" },
         { "firstname" : "Marc", "lastname" : "Johnson" }
      ] // end of sales array
    }

So you might have:

{"COLUMNS": [ 
  {"REGISTRATION_DT" : "19901212", "USERNAME" : "kudos", "PASSWORD" : "tx91!#1", ... },
  {"REGISTRATION_DT" : "19940709", "USERNAME" : "jenny", "PASSWORD" : "fxuf#2", ... },
  {"REGISTRATION_DT" : "20070110", "USERNAME" : "benji12", "PASSWORD" : "rabbit19", ... }
 ]
}

If the server is sending you something which you refer to as res, you can just do this to parse it in your Javascript:

var o=JSON.parse(res);

You can then cycle through each instance within columns like follows:

for (var i=0;i<o.COLUMNS.length;i++)
{  
        var date = o.COLUMNS[i].REGISTRATION_DT; .... 
}