Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - parsing JSON data - Having trouble with variable name

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?

like image 303
jyoseph Avatar asked Aug 05 '09 06:08

jyoseph


3 Answers

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

like image 77
Jason Berry Avatar answered Nov 10 '22 12:11

Jason Berry


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.

like image 26
redsquare Avatar answered Nov 10 '22 14:11

redsquare


Use the bracket notation to access the members:

var photo500 = this['photo-url-500']; 
like image 1
Christian C. Salvadó Avatar answered Nov 10 '22 12:11

Christian C. Salvadó