Reputation: 1448
I am trying to retreive the values present in the JSON Array.However,my code is failing to get it executed.Below posted is how the file looks like.
{
"meta" : {
"view" : {
"description" : "This data set shows the location of Baltimore City's Services.",
"columns" : [{
"cachedContents" : {
"top" : [{
"item" : "American Rescue Workers"
}
]
}
}
]
}
}
My Apologies if my JSON file has got some syntax issues.I am trying to access the item element present in cachedContents.Below posted is the code.
$(document).ready(function () {
$.get("https://data.baltimorecity.gov/api/views/hyq3-8sxr/rows.json", function (data) {
$.each(data.meta.view, function (i, obj) {
if (i == "name")
$("#result").append("<p align='center'>" + obj + "</p>");
if (i == "description")
$("#result").append("<p>" + obj + "</p>");
if (i == "columns")
$.each(obj.i.cachedContents, function (i1, obj) {
$("#result").append("<p>" + "hi" + "</p>");
});
});
});
});
Any suggestions would be highly helpful.
Upvotes: 0
Views: 62
Reputation: 34244
Your JSON contains a lot of fields, and iterating through them and using if
may have some performance issues.
You can directly access every member instead:
$(document).ready(function () {
$.get("https://data.baltimorecity.gov/api/views/hyq3-8sxr/rows.json", function (data) {
$("#result").append("<p align='center'>" + data.meta.view.name + "</p>");
$("#result").append("<p>" + data.meta.view.description + "</p>");
data.meta.view.columns.forEach(function(c) {
// here, 'c' is a column
$("#result").append("<p>Column " + c.name + "</p>");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
Upvotes: 3
Reputation: 8212
It should be
$.each(obj[0].cachedContents, function(i1, obj) {
$("#result").append("<p>" + "hi" + "</p>");
});
Object[0] not "i".
Upvotes: 1