SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Guru
    Join Date
    Jun 2009
    Posts
    826
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    JSON/jQuery -- am CONFUSED (about JSON..)

    I'm trying to learn JSON, it's more complicated than I thought...
    example here, jQuery.getJSON() – jQuery API works fine:

    Code:
    $.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

    Code:
    $.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...jsoncallback=?

    based on this tried to create my own example w/my own json, thus:
    Code:
    //	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:
    Code:
        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:

    1) in the Flickr example this line confuses me:

    Code:
    $.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?

    2) 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...jsoncallback=?)

    3) 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..

  2. #2
    SitePoint Guru
    Join Date
    Jun 2009
    Posts
    826
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    another thing that confuses me: in this line

    Code:
    $.getJSON('ajax/test.json', function(data) {
    (from here, jQuery.getJSON() – jQuery API)

    what data are we sending to the server? I thought this was for fetching data contained in a JSON object (test.json) that is already sitting on the server..


    further down in same example we have:

    Code:
    $.each(data, function(key, val) {
    now this data is data being fetched, no?? ;-) this is really is confusing....

    thank you...

  3. #3
    SitePoint Enthusiast rainner's Avatar
    Join Date
    Apr 2011
    Posts
    25
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The short answer is that "booksDiv" is not being targeted right..

    $( 'body' ).append( '<div id="booksDiv"></div>' );
    var booksDiv = $( '#booksDiv' );

    The longer answer..

    JSON is just string data. You can't do much with a string, so it needs to be parsed and converted into an Object for you to use it, that's what the $.getJSON() does, it fetches the JSON string, converts it to an object and hands you the object data for you to do whatever you want with it. That's where the function( data ) comes in. "data" is the object coming in from the JQuery parser..

    Have a look at the flickr JSON data..

    http://api.flickr.com/services/feeds...jsoncallback=?

    You'll see there's an array called "items":[], that's all the results you want. Now you have to loop through them and do what you want with them. The items object is being held in data.items, that's where this comes in..

    $.each( data.items, function( i, item ) { ... } );

    That's going to go over each of those items and hand you another object called "item". If you want to show the title you would find it in item.title, and so on..

  4. #4
    SitePoint Guru
    Join Date
    Jun 2009
    Posts
    826
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    well, if I only have one div on the it doesn't matter whether or not it has an id, no?? ;-) but well, my problem was an embarrassing one: I had book.json, but in code had books.json.. good grief... it's working now..
    JSON
    even added data.header ("List of Books");


    so: 'data' represents that entire JSON document (.json), or let us say, the "root" of all that JSON data, yes? (I guess it's equiv. to XML <root> yes???)

    even though got my example to work now, I still have questions:

    1) I don't understand why everyone says that JSON is just a 'string', JSON is a complex data structure, with arrays inside it among others.. this
    Code:
    {
    	"header": "List of Books",
    	"items" : [
    		{ "title": "title-1",
    			"author": "author-1" },
    		{ "title": "title-2",
    			"author": "author-2" }
            ]
    }
    doesn't look like a string to me...


    from JSON

    JSON is built on two structures:

    * A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
    * An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

    this doesn't describe a string to me....


    and that Flickr JSON certainly doesn't look like a string to me (you yourself say there's an array inside it..)



    2) you say, "'data' is the object coming in from the JQuery parser.. "
    so why does it say here, jQuery.getJSON() jQuery API that data is being sent to the server? oh brother, this is confusing..


    thank you very much.. slowly getting somewhere.. ultimately what I want to learn how to do ajax with JSON (pull data from db (MySQL, which I know already...;-) ), but first have to learn and understand JSON well...

  5. #5
    SitePoint Enthusiast rainner's Avatar
    Join Date
    Apr 2011
    Posts
    25
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    1.
    JSON is the representation of what an Object would be if it was a string. Same for XML, XHTML, they're all data that needs to be parsed prior to using. JSON is actually one of the more flexible ones when it comes to moving large sets of data around. You can only request one thing at a time, but if you pack a bunch of things in one string that be parsed on the other end you can get away with sending lots of stuff with one request.

    2.
    That's optional. With any type of AJAX data loading you need a callback function to be called when the request is done. The jQuery.getJSON() method takes 3 arguments, but the second one is optional and you can skip to only the URL and CALLBACK arguments. The callback has the data that's coming in.

    jQuery.getJSON( URL, DATA_TO_SEND, CALLBACK )

    or

    jQuery.getJSON( URL, CALLBACK )


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •