Javascript 使用jQuery在JSON结构中循环
我在通过jQuery循环JSON结构时遇到了一些问题 以下是我的JSON数据:Javascript 使用jQuery在JSON结构中循环,javascript,jquery,json,Javascript,Jquery,Json,我在通过jQuery循环JSON结构时遇到了一些问题 以下是我的JSON数据: { "suppliers": [ { "Supplier": { "id": "5704ebeb-e5e0-4779-aef4-16210a00020f", "name": "Gillmans", "mobile": "", "office
{
"suppliers": [
{
"Supplier": {
"id": "5704ebeb-e5e0-4779-aef4-16210a00020f",
"name": "Gillmans",
"mobile": "",
"office_telephone": "00000",
"ooh_contact": "00000",
"fax_number": "",
"address_line_1": "St Oswalds Road",
"address_line_2": "Gloucester",
"address_line_3": "",
"address_line_4": "",
"postcode": "GL1 2SG",
"email": "email@example.com",
"contact": "",
"position": "",
"aov": "180.00",
"engineer": false,
"cc_on_new_job_emails": true,
"can_add_quotes": false,
"notes": "",
"status": "1",
"created": "2016-04-06 11:58:51",
"modified": "2016-07-27 11:23:01",
"status_text": "Active",
"engineer_text": "No",
"cc_on_new_job_emails_text": "Yes"
},
"Trade": [],
"PostcodeArea": []
},
{
"Supplier": {
"id": "571e390f-91e8-4745-8f78-168b0a00020f",
"name": "Kings",
"mobile": "",
"office_telephone": "00000",
"ooh_contact": "0000",
"fax_number": "",
"address_line_1": "",
"address_line_2": "",
"address_line_3": "",
"address_line_4": "",
"postcode": "",
"email": "",
"contact": "",
"position": "Account Manager; Joanne Brook",
"aov": null,
"engineer": false,
"cc_on_new_job_emails": false,
"can_add_quotes": false,
"notes": "",
"status": "1",
"created": "2016-04-25 16:34:39",
"modified": "2016-07-08 15:22:15",
"status_text": "Active",
"engineer_text": "No",
"cc_on_new_job_emails_text": "No"
},
"Trade": [],
"PostcodeArea": []
}
]
}
这个JSON是在名为data
的变量中从AJAX调用返回的data
是一个Javascript对象,即它已经被ajax调用解析过了
我试图循环浏览这个JSON数据并获取name
和id
属性。我是这样做的:
$.each(data, function(k, v) {
$.each(this, function(key, val) {
$.each(this, function(key2, val2) {
$.each(this, function(key3, val3) {
if(key3 == 'name')
{
alert(val3);
}
});
});
});
});
这将打印所有的name
值,但显然这是一种非常混乱的方式,我想知道是否有更简单的方法可以获取此结构的name
和id
属性并将其存储在变量中?您可以处理以下问题:
试试这个:
var data = {
"suppliers":[
{
"Supplier":{
"id":"5704ebeb-e5e0-4779-aef4-16210a00020f",
"name":"Gillmans"
},
"Trade":[
],
"PostcodeArea":[
]
},
{
"Supplier":{
"id":"571e390f-91e8-4745-8f78-168b0a00020f",
"name":"Kings"
},
"Trade":[
],
"PostcodeArea":[
]
}
]
}
$.each(data.suppliers, function(k, v) {
alert(this.Supplier.id);
})
这个似乎是为我做的,下面的答案抛出了一个错误。所以它不是JSON。JSON!==Javascript对象在控制台中抛出一个错误
57bc12cc-4d4c-4063-9b3c-54369a44812a:1未捕获的语法错误:JSON中的意外标记o位于位置1
您没有澄清数据是字符串还是对象?该错误似乎暗示它是一个对象,因此根本不是JSON。
$.each(data.suppliers, function(){
alert(this.Supplier.id);
});
var data = {
"suppliers":[
{
"Supplier":{
"id":"5704ebeb-e5e0-4779-aef4-16210a00020f",
"name":"Gillmans"
},
"Trade":[
],
"PostcodeArea":[
]
},
{
"Supplier":{
"id":"571e390f-91e8-4745-8f78-168b0a00020f",
"name":"Kings"
},
"Trade":[
],
"PostcodeArea":[
]
}
]
}
$.each(data.suppliers, function(k, v) {
alert(this.Supplier.id);
})