【发布时间】:2018-04-15 12:56:26
【问题描述】:
我有从 PHP Curl jSon 获取的数据。
以下是json数据示例。
这是数据:
{
"rajaongkir": {
"query": {
"origin": "23",
"destination": "152",
"weight": 1500,
"courier": "all"
},
"status": {
"code": 200,
"description": "OK"
},
"origin_details": {
"city_id": "23",
"province_id": "9",
"province": "Jawa Barat",
"type": "Kota",
"city_name": "Bandung",
"postal_code": "40000"
},
"destination_details": {
"city_id": "152",
"province_id": "6",
"province": "DKI Jakarta",
"type": "Kota",
"city_name": "Jakarta Pusat",
"postal_code": "10000"
},
"results": [
{
"code": "pos",
"name": "POS Indonesia (POS)",
"costs": [
{
"service": "Surat Kilat Khusus",
"description": "Surat Kilat Khusus",
"cost": [
{
"value": 16500,
"etd": "2-4",
"note": ""
}
]
},
{
"service": "Express Next Day",
"description": "Express Next Day",
"cost": [
{
"value": 22000,
"etd": "1",
"note": ""
}
]
}
]
},
{
"code": "jne",
"name": "Jalur Nugraha Ekakurir (JNE)",
"costs": [
{
"service": "OKE",
"description": "Ongkos Kirim Ekonomis",
"cost": [
{
"value": 18000,
"etd": "2-3",
"note": ""
}
]
},
{
"service": "REG",
"description": "Layanan Reguler",
"cost": [
{
"value": 20000,
"etd": "1-2",
"note": ""
}
]
},
{
"service": "YES",
"description": "Yakin Esok Sampai",
"cost": [
{
"value": 30000,
"etd": "1-1",
"note": ""
}
]
}
]
},
{
"code": "tiki",
"name": "Citra Van Titipan Kilat (TIKI)",
"costs": [
{
"service": "SDS",
"description": "Same Day Service",
"cost": [
{
"value": 135000,
"etd": "",
"note": ""
}
]
},
{
"service": "HDS",
"description": "Holiday Delivery Service",
"cost": [
{
"value": 49000,
"etd": "",
"note": ""
}
]
},
{
"service": "ONS",
"description": "Over Night Service",
"cost": [
{
"value": 26000,
"etd": "",
"note": ""
}
]
},
{
"service": "REG",
"description": "Regular Service",
"cost": [
{
"value": 17000,
"etd": "",
"note": ""
}
]
},
{
"service": "ECO",
"description": "Economi Service",
"cost": [
{
"value": 14000,
"etd": "",
"note": ""
}
]
}
]
}
]
}
}
现在我想获取结果数据 -> 成本 -> 服务,然后从结果 -> 成本 -> 成本 -> 值中获取成本值并将其附加到组合框上。
$.each(jsonStr['rajaongkir']['results'], function(i,n){
cou = '<option value="'+n['costs']['description']+'">'+n['costs']['description']+'</option>';
cou = cou + '';
$("#service").append(cou);
});
我试图运行上面的代码并得到undefined 值。
有什么方法可以得到吗?
【问题讨论】:
-
“results”和“costs”是数组,需要通过索引来访问,即results[0].costs[0].description为第一个结果和第一个cost
-
@SamLittlefair 你能举个例子吗?
-
使用您的语法:n[0]['costs'][0]['description'],将 0 替换为您要访问的数组索引
-
抱歉尝试 n['costs'][0]['description']
-
使用:n['costs'][0]['cost'][0]['value'],现在作为答案发布,谢谢:)