简体   繁体   English

jQuery - 解析JSON数据 - 变量名称有问题

[英]jQuery - parsing JSON data - Having trouble with variable name

My first delve into working with JSON data. 我第一次尝试使用JSON数据。 I have a bit of experience using jQuery though. 我有一些使用jQuery的经验。

I'm posting to this URL (tumblr api): jyoseph.com/api/read/json 我发布到这个URL(tumblr api):jyoseph.com/api/read/json

What I'm trying to do is output the json that gets returned. 我要做的是输出返回的json。 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 请参阅我的jsbin帖子了解整个脚本: http ://jsbin.com/utaju/edit

Some of the keys from tumblr have "-" hyphens in them, and that seem to be causing a problem. 来自tumblr的一些键在其中有“ - ”连字符,这似乎导致了一个问题。 As you can see "photo-url-500" or another "photo-caption" is causing the script to break, it's outputting NaN. 正如你可以看到“photo-url-500”或其他“照片标题”导致脚本中断,它正在输出NaN。

Is there a problem with having hyphens in the key names? 在密钥名称中使用连字符是否有问题? Or am I going about this all wrong? 或者我这样做是错的?

If there are dashes in the names you'll need to access them differently. 如果名称中有破折号,则需要以不同方式访问它们。 Change var photo500 = this.photo-url-500; 改变var photo500 = this.photo-url-500; to read var photo500 = this["photo-url-500"]; 阅读var photo500 = this["photo-url-500"]; .

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. 附加到dom是昂贵的。

使用括号表示法访问成员:

var photo500 = this['photo-url-500']; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM