2017-06-14 82 views
0

我有一個本地文件中的以下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只..

+4

你的JSON不正確,'inputs'必須到數組 –

+1

改變措辭略有不同:你在JS對象中不能有重複的鍵。或者一個JSON對象。 –

+2

您無法在JSON中使用重複密鑰,請嘗試使用JSONLint在線工具 – dloeda

回答

0

您的JSON是不正確的, 你不能用JSON對象有2個按鍵相同(輸入) 如果有2個identicals鍵;第一個被最後一個覆蓋。

將其轉換爲數組或更改您的密鑰名稱。

3

正確的json到:

{ 
    "fields": { 
     "input": [{ 
       "name": "txtCpf", 
       "id": "txtCpf", 
       "value": "", 
       "type": "text", 
       "Mask": "000.000.000-00", 
       "class": "input" 
      }, 
      { 
       "name": "txtTelephone", 
       "id": "txtTelefone", 
       "value": "", 
       "type": "text", 
       "Mask": "(00) 00000-0000", 
       "class": "input" 
      } 
     ], 
     "button": { 
      "name": "btnSave", 
      "id": "btnSave", 
      "value": "", 
      "class": "input" 
     } 
    } 
} 

檢索所有的輸入名字,改變你的腳本:

myObj.fields.input.forEach(function (item) { 
    console.log(item.name); 
}) 
+0

這仍然沒有回答這個問題:如何**取回所有的名字? –

+0

@FlorianAlbrecht我猜Json是固定的,目前的JavaScript已經可以做到這一點。 – Nope

+0

@Fran nope,不是現在的形式。 –