How to read JSON(server response) in Javascript?
Asked Answered
U

6

21

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!

Unrest answered 18/3, 2012 at 1:4 Comment(0)
C
13

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; .... 
}
Crescent answered 18/3, 2012 at 1:15 Comment(1)
giving me syntax error on line var o=JSON.parse(res); please suggest. I am trying with simple javascript and IE8Pat
K
6

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
Koeppel answered 16/12, 2016 at 6:43 Comment(0)
I
3

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.

Infrastructure answered 18/3, 2012 at 1:16 Comment(1)
If you have a way of changing the format the server responds, to make it look more like what Nick suggests, I recommend that. The format you've got now is pretty fugly to work with.Infrastructure
K
2

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))
    })
Kola answered 29/7, 2017 at 19:30 Comment(0)
K
1

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/

Knurled answered 18/3, 2012 at 1:15 Comment(0)
S
1

Just use JSON.parse(serverResponse)

Sleekit answered 19/8, 2017 at 8:9 Comment(2)
This is a too short answer. It will be more useful as a comment. Please expand the explanation of you solution. For example, what is serverResponse? The OP didn't mentioned such a variable, and you don't explain it.Bonis
You are awesome!Prom

© 2022 - 2024 — McMap. All rights reserved.