Reputation: 120
Why is my JSON not working? I tried
In the dom and js I have:
<div class="compare-table-data" data-compare-table='
{
{
"naam":"Ford",
"id":"BMW",
"eig":{
"test":"wert"
},
},
{
"naam":"Ford",
"id":"BMW",
"eig":{
"test":"wert"
},
}
}'></div>
var jsonArray = $('.compare-table-data').data('compare-table'),
table = '';
for (var item in jsonArray){
table += item["naam"];
}
}
$("#compareTable").append(table);
Result... a whole lot of: undefinedundefinedundefinedundefinedundefinedundefinedundefined
Upvotes: 0
Views: 77
Reputation: 1322
your JSON was incorrect it should be array of objects,
and for in
loop should be used to loop through object nt array,
for
is better here
<div class="compare-table-data" data-compare-table='
[
{
"naam":"Ford",
"id":"BMW",
"eig":{
"test":"wert"
}
},
{
"naam":"Ford",
"id":"BMW",
"eig":{
"test":"wert"
}
}
]'></div>
var jsonArray = $('.compare-table-data').data('compare-table'),
table = '';
jsonArray = $.parseJSON(jsonArray );
for (var i=0;i<jsonArray.length;i++){
table += jsonArray[i]["naam"];
}
}
$("#compareTable").append(table);
Upvotes: 1
Reputation: 156
You should change {} braces to [] as you have an array, remove unnecessary commas inside the JSON, change for-in loop (used to iterate over properties of an object) to for-of (used to iterate over elements of an array)
<div class="compare-table-data" data-compare-table='[
{
"naam":"Ford",
"id":"BMW",
"eig":{
"test":"wert"
}
},
{
"naam":"Ford",
"id":"BMW",
"eig":{
"test":"wert"
}
}
]'></div>
var jsonArray = $('.compare-table-data').data('compare-table'), table = '';
for (var item of jsonArray){
table += item["naam"];
}
$("#compareTable").append(table);
Upvotes: 0