我得到了JSON格式的结果,其中对象可以在数组内,对象在对象内或类似类型的场景中。如何使用JQuery提取可能在数组或对象内或相同的任何特定值。
下面是存储在变量result中的JSON示例。
var result= {
"to_station": {
"name": "ANAND VIHAR TERMINAL",
"lat": 28.6118176,
"lng": 77.2888291,
"code": "ANVT"
},
"train": {
"name": "VIKRAMSHILA EXP",
"classes": [
{
"name": "3rd AC ECONOMY",
"available": "N",
"code": "3E"
},
{
"name": "FIRST CLASS",
"available": "N",
"code": "FC"
},
{
"name": "FIRST AC",
"available": "Y",
"code": "1A"
},
{
"name": "SECOND AC",
"available": "Y",
"code": "2A"
},
{
"name": "SECOND SEATING",
"available": "N",
"code": "2S"
},
{
"name": "AC CHAIR CAR",
"available": "N",
"code": "CC"
},
{
"name": "SLEEPER CLASS",
"available": "Y",
"code": "SL"
},
{
"name": "THIRD AC",
"available": "Y",
"code": "3A"
}
],
"days": [
{
"runs": "Y",
"code": "MON"
},
{
"runs": "Y",
"code": "TUE"
},
{
"runs": "Y",
"code": "WED"
},
{
"runs": "Y",
"code": "THU"
},
{
"runs": "Y",
"code": "FRI"
},
{
"runs": "Y",
"code": "SAT"
},
{
"runs": "Y",
"code": "SUN"
}
],
"number": "12367"
},
"from_station": {
"name": "BHAGALPUR",
"lat": 25.2494829,
"lng": 86.9828131,
"code": "BGP"
},
"quota": {
"name": "GENERAL QUOTA",
"code": "GN"
},
"availability": [
{
"status": "GNWL37/WL24",
"date": "25-8-2018"
},
{
"status": "GNWL17/WL10",
"date": "26-8-2018"
},
{
"status": "GNWL14/WL11",
"date": "27-8-2018"
},
{
"status": "GNWL3/RAC19",
"date": "28-8-2018"
},
{
"status": "RAC 9/RAC 7",
"date": "29-8-2018"
},
{
"status": "AVAILABLE-0017",
"date": "30-8-2018"
}
],
"debit": 3,
"response_code": 200,
"journey_class": {
"name": "THIRD AC",
"code": "3A"
}
}
假设我想提取所有结果日期的状态(内部可用性),那么我应该如何使用JQuery进行同样的操作。
答案 0 :(得分:0)
如果使用jQuery,则可以尝试以下操作:
$.each(result.availability, function(idx, data){
//status is available as data.status
console.log(data.date + ' ' + data.status);
});
您还可以使用普通的javascript实现相同的功能:
for(var idx in result.availability){
//status is available as result.availability[idx].status
console.log(result.availability[idx].date + ' ' + result.availability[idx].status);
}
希望这会有所帮助。