Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read JSON(server response) in Javascript?

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!

like image 663
BlackM Avatar asked Mar 18 '12 01:03

BlackM


People also ask

How do I get JSON response?

To request JSON from a URL, you need to send an HTTP GET request to the server and provide the Accept: application/json request header with your request. The Accept header tells the server that our client is expecting JSON.

What is response JSON () in JavaScript?

Response.json()It returns a promise which resolves with the result of parsing the body text as JSON . Note that despite the method being named json() , the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object.

How extract JSON data from fetch response?

To get JSON from the server using the Fetch API, you can use the response. json() method. The response. json() method reads the data returned by the server and returns a promise that resolves with a JSON object.


1 Answers

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; .... 
}
like image 79
Nick Avatar answered Oct 09 '22 08:10

Nick