[英]Convert JSON array to object or access certain nodes on JSON array?
我正在使用jQuery向MVC控制器發出ajax請求,然后該MVC控制器提交了一個對象,並返回了該對象的JSON表示形式,該對象已返回給ajax請求。 返回的JSON如下所示:
[
{
"Account_LocationDevices": [],
"Account_ChannelTransactions": [],
"Account_Location_PaymentTypes": [],
"ID": 56,
"AccountID": 1,
"Name": "b",
"Address1": "",
"Address2": "",
"City": "",
"State": "",
"ZipCode": "",
"Country": "",
}
]
然后,我需要能夠訪問此JSON數組的某些“節點”,或將其轉換回對象並通過該對象進行訪問。 任何人都對如何獲取此JSON結果並將其轉換回對象或訪問數組的某些部分有任何建議,以防萬一更改架構而無需使用索引號?
這是jQuery做的工作
$.ajax({
type: "POST",
url: "../Company/MicrosoftRMSStoreOperations",
data: { locationName: inputValue },
datatype: "json",
beforeSend: function () {
},
success: function (data) {
alert("Location successfully added!");
$('#locationDropDown').append(
$('<option></option>').val().html()
);
$('#inputAddLocation').val("");
$('#AddLocation').animate({
width: 'toggle',
}, 100, function() {
//after animation
});
// window.location.href = window.location.href;
},
error: function () {
alert("Appears the database Gods did not agree");
}
});
首先,這不是json響應,這是一個示例:
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
如果您使用Jquery的$ .post方法,則可以將最后一個參數指定為'json',然后可以獲得諸如以下的元素:(我假設您在控制器代碼中提供了json結構)
var loc = data.Account_LocationDevices;
我成功添加了這一行:
var json = $.parseJSON(data);
然后,我可以像這樣訪問數組“ json [0] .ID”或“ json [0] .Name”
最后看一下實現的代碼...
$.ajax({
type: "POST",
url: "../Company/MicrosoftRMSStoreOperations",
data: { locationName: inputValue },
datatype: "json",
beforeSend: function () {
},
success: function (data) {
var json = $.parseJSON(data);
alert("Location successfully added!");
$('#locationDropDown').append(
$('<option></option>').val(json[0].ID.toString()).html(json[0].Name)
);
$('#inputAddLocation').val("");
$('#AddLocation').animate({
width: 'toggle',
}, 100, function() {
//after animation
});
// window.location.href = window.location.href;
},
error: function () {
alert("Appears the database Gods did not agree");
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.