I’m trying to learn JSON, it’s more complicated than I thought…
example here, jQuery.getJSON() – jQuery API works fine:
$.getJSON('test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<span id="' + key + '">' + val + '</span><br />');
});
$('<div/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
then found a Flick example here, Ajax/jQuery.getJSON - jQuery JavaScript Library
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
function(data){
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 3 ) return false;
});
});
this also works fine, photos show up… but I had no way to see what exactly was in that Flickr json, till I found this:
How to use jQuery with a JSON Flickr feed to display photos | Richard Shepherd
and json is here:
http://api.flickr.com/services/feeds/groups_pool.gne?id=998875@N22&lang=en-us&format=json&jsoncallback=?
based on this tried to create my own example w/my own json, thus:
// books.json:
{
"header": "List of Books",
"items" : [
{ "title": "title-1",
"author": "author-1" },
{ "title": "title-2",
"author": "author-2" }
]
}
and tried to pull from this json thus:
var booksDiv = "<div></div>";
$('body').append(booksDiv);
$.getJSON('books.json', function(data) {
$.each(data.items, function(i,item) { // "items", "item".. confusing naming convention....;-)
booksDiv.append('<span>' + item.title + ' - by - ' + item.author + '</span><br />');
});
});
but this is not working, the div is not getting populated
now I have various questions:
- in the Flickr example this line confuses me:
$.each(data.items, function(i,item)
does ‘data.items’ refer to the “items” element inside the Flickr json? or is it a generic reference to every item in the json?
(“title”, “link”, etc) and what does “item” refer to in the fn-call (function(i,item) )? to “item” element inside the json?
- don’t understand why this data.item.media.m isn’t data.items.media.m (itemS plural in 2nd example)
(again, I mean this json:
http://api.flickr.com/services/feeds/groups_pool.gne?id=998875@N22&lang=en-us&format=json&jsoncallback=?)
- and why is this entire Flickr json wrapped in “(…)” ???
pls enlighten me…
I hope this post makes sense… this is complicated stuff… I can’t compose a simple post about it…
thank you…