BlackM
BlackM

Reputation: 4065

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!

Upvotes: 21

Views: 118598

Answers (6)

Umar Asghar
Umar Asghar

Reputation: 4064

Please take a look on example code snippet as shown below

Example JSON

{
"name": "mkyong",
"age": 30,
"address": {
    "streetAddress": "88 8nd Street",
    "city": "New York"
},
"phoneNumber": [
    {
        "type": "home",
        "number": "111 111-1111"
    },
    {
        "type": "fax",
        "number": "222 222-2222"
    }
]
}

Here is the code to read the json

<script>
   var data = '{"name": "mkyong","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';

var json = JSON.parse(data);
        
alert(json["name"]); //mkyong
alert(json.name); //mkyong

alert(json.address.streetAddress); //88 8nd Street
alert(json["address"].city); //New York
        
alert(json.phoneNumber[0].number); //111 111-1111
alert(json.phoneNumber[1].type); //fax
        
alert(json.phoneNumber.number); //undefined

Upvotes: 7

Alberto Camargo
Alberto Camargo

Reputation: 149

Just use JSON.parse(serverResponse)

Upvotes: 1

user8387204
user8387204

Reputation:

If you got here trying to find out how to read from [Response object] (as I did) - this what can help: - if you use fetch don't forget about res.json() before logging in console

fetch(`http://localhost:3000/data/${hour}`, {
        method: 'get'
    })
    .then(res => {
        return res.json()
      })
    .then((response) => {
        console.log('res: ' + JSON.stringify(response))
    })

Upvotes: 3

Nick
Nick

Reputation: 6025

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; .... 
}

Upvotes: 13

Mike Ruhlin
Mike Ruhlin

Reputation: 3556

JSON objects work just like any normal javascript objects or dictionaries

// You can do it this way
var data = this.responseData["DATA"]
// Or this way
var data = this.responseData.DATA

In your case, COLUMNS and data are both arrays, so it looks like you're trying to get the element from data that corresponds to the "FNAME" element in COLUMNS?

var columns = this.responseData["COLUMNS"];
var data = this.responseData["DATA"][0];

for(var i=0; i<columns.length; i++){
    if(columns[i] == "FNAME"){
        Ti.API.log(data[i]);
    }
}

EDIT: If you can't change the data on the server end, you can make your own object client side. This also helps if you have to refer to multiple columns (which you probably do).

var columns = this.responseData["COLUMNS"];
var data = this.responseData["DATA"][0];
var realData = {};

for(var i=0; i<columns.length; i++){
    realData[columns[i]] = data[i];
}

// Now you can access properties directly by name.
Ti.API.log(data.FNAME);

More edit: My answers only consider the first row in DATA, because I misread originally. I'll leave it up to you to figure out how to process the others.

Upvotes: 3

stan
stan

Reputation: 4995

Testing out your code in http://jsonlint.com/, it says that your server's response is not a valid JSON string.

Additionally, I recommend checking out jQuery.parseJSON http://api.jquery.com/jQuery.parseJSON/

Upvotes: 1

Related Questions