views:

1472

answers:

4

My first delve into working with JSON data. I have a bit of experience using jQuery though.

I'm posting to this URL (tumblr api): jyoseph.com/api/read/json

What I'm trying to do is output the json that gets returned. What I have so far:

$(document).ready(function(){ 

$.getJSON("http://jyoseph.com/api/read/json?callback=?", 
  function(data) { 
    //console.log(data); 
    console.log(data.posts);         

      $.each(data.posts, function(i,posts){ 
        var id = this.id; 
        var type = this.type; 
        var date = this.date; 
        var url = this.url; 
        var photo500 = this.photo-url-500; 

        $('ul').append('<li> ' +id+ ' - ' +type+ ' - ' +date+ ' - ' +url+ ' - ' +photo500+ ' - ' + ' </li>'); 
      }); 

  }); 

});

See my jsbin post for the entire script: http://jsbin.com/utaju/edit

Some of the keys from tumblr have "-" hyphens in them, and that seem to be causing a problem. As you can see "photo-url-500" or another "photo-caption" is causing the script to break, it's outputting NaN.

Is there a problem with having hyphens in the key names? Or am I going about this all wrong?

+6  A: 

If there are dashes in the names you'll need to access them differently. Change var photo500 = this.photo-url-500; to read var photo500 = this["photo-url-500"];.

Jason Berry
Works perfectly, thank you much!
jyoseph
+1  A: 

Use the bracket notation to access the members:

var photo500 = this['photo-url-500'];
CMS
Thank you for the link, very helpful, looking over that now.
jyoseph
+2  A: 

Please note it is best not to append inside each iteration. Better to append to a string or push to an array then append once after the iterator has finished. Appending to the dom is expensive.

redsquare
So I should build a string with each iteration and then output the final string? That's solid advice, I didn't think about that. Thanks!
jyoseph
A: 

Maybe this will help - I posted a simple example of pulling the last 5 posts from the tumblr JSON api data. link text

Morning Cat Media