Reputation: 103
I have the following json in a local file:
{
"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"
}
}
}
This is my javascript code:
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();
This myObj.fields.input.name
is returning only the last position of the input
object so it shows txtTelephone
Would like a return of all objects of the input and not only of the last element
Using javascript only..
Upvotes: 0
Views: 93
Reputation: 129
Correct json to :
{
"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"
}
}
}
to retrieve all input names, change your script to:
myObj.fields.input.forEach(function (item) {
console.log(item.name);
})
Upvotes: 3
Reputation: 5064
Your json is not correct, You can't have with a json object 2 keys identical (input) If there is 2 identicals keys; the first one is overwritten with the last one.
Convert it to an array for example or change your key name.
Upvotes: 0