简体   繁体   中英

How to retrieve JSON values to Javascript

I'm trying to retrieve the JSON data given below but I'm unable to.

Since I'm using Javascript Ajax success function, when I try doing alerts with the code,

$.ajax({
type:'GET',
url:myURL,
success : function(data) {
     alert(data);
     //{"object1":{"mainIsActive":"A","mainBuildingGL":"01493","mainIsUnderCons":"B"},"object2":[[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],{"newBuildingGL":"15450"}]}
}
});

I am retrieving the below JSON data.

{"object1":{"mainIsActive":"A","mainBuildingGL":"01493","mainIsUnderCons":"B"},"object2":[[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],{"newBuildingGL":"15450"}]}

But when I try trying to get the value of mainIsActive using:

alert(data.object1.mainIsActive);

I am getting the error in the console:

"Cannot read property 'mainIsActive' of undefined at Object.success (:143:30)"

Can you please help? I also attached the JSON image so you can understand the structure better.

在此处输入图片说明

使用语法解析后,JSON数据将在对象结构中可用

JSON.parse(StringYouWantToParse)

This code seems to work properly:

var x = '{"object1":{"mainIsActive":"A","mainBuildingGL":"01493","mainIsUnderCons":"B"},"object2":[[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],{"newBuildingGL":"15450"}]}';
var data = JSON.parse(x); 
alert(data.object1.mainIsActive);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM