I have a bunch of JSON data that I'd like to output on a page. I've seen so many variations on how this could be setup (and can change it), I'm not sure this is the best way for what I'm doing, but it validates in a JSON linter.
{
"data": {
"typeA": [
{
"name":"Thing 1",
"link":"#"
},
{
"name":"Thing 2",
"link":"#"
}
],
"typeB": [
{
"name":"Thing iii",
"link":"#"
}
],
"typeC": [
{
"name":"Thing iv",
"link":"#"
}
]
}
}
I've tried to have this JSON in its own .js file, but actually had more luck keeping it in the document (it's a one-pager site anyways) - by "more luck" I mean I had this kind of working when I only had typeA.
Later within a document ready I have the following jQuery - which when executed tells me that data is not defined.
$.each(data, function(i, v) {
$('#output').append("<p><a href='" + v.link + "'>" + v.name + "</a></p>");
});
I'm sure I'm missing something big here! I'd love the following:
- Some clues as to what I need to do to get this working at all - and ideally that I could output typeA into #Output, and typeB, and typeC elsewhere, like #Output2
- Some definitions / terms to the stuff or parts at play here. I really don't know what I don't know here and would love to read up on this more!
Thanks
2 Answers 2
In your case assuming data is the variable referencing to the above object, you need to iterate through data.data since the outer object has only one key called data which contains types.
Then the type values like typeA is again a array, so to access the value like link you need to access the first index of the array using v[0].link
You need to use
$.each(data.data, function(i, v) {
$('#output').append("<p><a href='" + v[0].link + "'>" + v[0].name + "</a></p>");
});
Demo: Fiddle
Try beloe code
$(json['data']).each(function (index, value) {
for (i in value) {
$(value[i]).each(function (i, v) {
alert(v['name']);
alert(v['link']);
});
}
})
fiddle http://jsfiddle.net/xppxZ/1/
datacome from? The rest of this is (so far) irrelevant. Could you provide an SSCCE?