开发者

Jquery data retrival returns null with json data

开发者 https://www.devze.com 2023-02-01 18:49 出处:网络
I have below sample json file: {\"jsonData\":{\"REC\":[{\"TEST\":\"T\",\"TEST1\":\"T1\",\"TEST2\":\"T2\"},{\"R\":\"R\",\"R1\":\"R1\",\"R3\":\"R3\"}],

I have below sample json file: {"jsonData":{"REC":[{"TEST":"T","TEST1":"T1","TEST2":"T2"},{"R":"R","R1":"R1","R3":"R3"}], "DATA":{"FIRST":0,"SEC":1}}}.

I want to retrieve data from json file,i am try like below,but it is giving null.

from res开发者_开发技巧ult object:i am retrieving data like below:

to retrive the value T: this.jsonData.REC.TEST

To retrieve the value R1: this.jsonData.DATA.FIRST

Please correct me if i am doing any wrong.

Thanks in Advance.


No the REC key has an array of Objest so it should be:
for the value T: json.jsonData.REC[0].TEST
for the value R1: json.jsonData.REC[1].R1
Example Link
P.S: please use the code tag next time, happy holidays! :)


You should be parsing this in an Ajax response by either using getJSON method or if using Ajax, you should use dataType as json. In the success callback the parsed json result can be accessed through the response object. So you should be using some thing like resp.jsonData.REC[0].Test not using this.


If the json file doesn't assign the object to a variable then the only way I can think of is using an Ajax query to read the contents of the file and processing the object as follows:

jQuery:

$.getJSON("<PATH_TO_YOUR_JSONFILE>",
        function(data){
          alert(jsonObj.jsonData.REC.TEST);     
                    alert(jsonObj.jsonData.DATA.FIRST);
        });

With pure js:

var jsonObj = {};
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function()
  {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
            eval("jsonObj = " + xmlhttp.responseText);
            checkJson();
    }
  }
xmlhttp.open("GET","<PATH_TO_YOUR_JSONFILE>",true);
xmlhttp.send();

function checkJson()
{
    alert(jsonObj.jsonData.REC.TEST);
    alert(jsonObj.jsonData.DATA.FIRST);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号