Question

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?

Was it helpful?

Solution

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"];.

OTHER TIPS

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.

Use the bracket notation to access the members:

var photo500 = this['photo-url-500']; 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top