Fetching data from JSON.parse array

我与影子孤独终老i 提交于 2019-12-02 11:31:30

问题


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?


回答1:


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"]);


来源:https://stackoverflow.com/questions/9129776/fetching-data-from-json-parse-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!