Search code examples
javascriptjsontitaniumappcelerator

Fetching data from JSON.parse array


I am stuck in this problem, I am calling a webService that returns me a json response.

now i want to fetch a particular value from that response but after searching on internet and struggling a lot couldn't fix it.

here is my code:

var xhr = Titanium.Network.createHTTPClient({

onload : function(e) {
     Ti.API.info("Received text: " + this.responseText);
     alert('success');
     },
 // function called when an error occurs, including a timeout
 onerror : function(e) {
     Ti.API.debug(e.error);
     alert('error');
 },
 timeout : 5000
});

var data = {"data":"system.connect"};
xhr.open("POST","http://mytesturl.net/services/json");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
xhr.send("method=system.connect");

The response is like this:

{"#error":false,"#data":{"sessid":"c4likn6vg33hngbpmobisrsbpcjjmf39","user":{"uid":0,"hostname":"102.119.85.120","roles":{"1":"anonymous user"},"session":"","cache":0}},"#response_code":200}

from the above response I want to fetch the sessid value. what is the right approach?


Solution

  • The following can be viewed and tested on jsfiddle.net.

    // Given a string of JSON called responseText
    var responseText = '{"#error":false,"#data":{"sessid":"c4likn6vg33hngbpmobisrsbpcjjmf39","user":{"uid":0,"hostname":"102.119.85.120","roles":{"1":"anonymous user"},"session":"","cache":0}},"#response_code":200}';
    
    // You can parse it to an object using JSON.parse
    var responseObj = JSON.parse(responseText);
    
    // And then access the properties as with any object
    console.log(responseObj ["#data"]["sessid"]);