Reputation: 2074
I have a json file like this :
[
{
"X_id": [ "id1" ],
"contents.value": [ "AA" ],
"contents.count": [ 95 ]
},
{
"X_id": [ "id2" ],
"contents.value": [ "BB" ],
"contents.count": [ 41 ]
},
{
"X_id": [ "id3" ],
"contents.value": [ "CC" ],
"contents.count": [ 36 ]
},
{
"X_id": [ "id4" ],
"contents.value": [ "DD" ],
"contents.count": [ 4 ]
},
{
"X_id": [ "id5" ],
"contents.value": [ "EE" ],
"contents.count": [ 33 ]
}
]
and I want to display this values on my html page, and for the test I try first to show them in console :
$.getJSON("example.json", function(data) {})
.done(function(data) {
$.each(data.items, function(i, item) {
console.log(item.contents.value);
});
})
.fail(function() {
console.log("error");
})
.always(function(data) {
console.log(data);
});
but I get this error message :
TypeError: a is undefined
...rCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d...
How can I solve this problem ?
Upvotes: 0
Views: 1124
Reputation: 816272
Your data is an array of objects. Yet you are trying to pass data.items
to $.each
. Arrays don't have such a property:
> var data = [];
> data.items
undefined
You probably want to pass data
itself to $.each
.
See also Access / process (nested) objects, arrays or JSON .
Wrt to console.log(item.contents.value);
(which is wrong), have a look at How to access object properties containing special characters? .
Upvotes: 1
Reputation: 112
following code working fine check it once , why your getting error because of get json data is array object not so need to pass data[0] then you can iterate ,in key value pairs value is again array.
<!DOCTYPE html>
<html>
<head>
<title>Consoling Json Array</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-1.11.3.js" type="text/javascript"></script>
</head>
<body>
<div>TODO write content</div>
<script>
$.getJSON("example.json", function (data) {
console.log(data);
})
.done(function (data) {
$.each(data[0], function (i, item) {
console.log(i,item[0]);
});
})
.fail(function () {
console.log("error");
})
.always(function (data) {
console.log(data);
});
</script>
</body>
Upvotes: 0
Reputation: 5657
Arrays don't have an items
property. Just use data
instead:
$.getJSON("example.json", function(data) {})
.done(function(data) {
$.each(data, function(i, item) {
console.log(item.contents.value);
});
})
.fail(function() {
console.log("error");
})
.always(function(data) {
console.log(data);
});
Upvotes: 0