我有一個本地文件中的以下JSON:不正確的返回JSON對象
{
"fields": {
"input": {
"name": "txtCpf",
"id": "txtCpf",
"value": "",
"type": "text",
"Mask": "000.000.000-00",
"class": "input"
},
"input": {
"name": "txtTelephone",
"id": "txtTelefone",
"value": "",
"type": "text",
"Mask": "(00) 00000-0000",
"class": "input"
},
"button": {
"name": "btnSave",
"id": "btnSave",
"value": "",
"class": "input"
}
}
}
這是我的javascript代碼:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.fields.input.name;
Object.keys(myObj).forEach(function (item) {
console.log(myObj.fields.input);
});
/* myObj.foreach(function(input){
var fields = input.fields;
alert(fields);
}); */
}
};
xmlhttp.open("GET", "mock.json", true);
xmlhttp.send();
這myObj.fields.input.name
是隻返回input
對象的最後位置,它顯示txtTelephone
想要返回的所有對象的輸入,而不僅僅是最後的el EMENT
使用JavaScript只..
你的JSON不正確,'inputs'必須到數組 –
改變措辭略有不同:你在JS對象中不能有重複的鍵。或者一個JSON對象。 –
您無法在JSON中使用重複密鑰,請嘗試使用JSONLint在線工具 – dloeda