Сбой с помощью JSON

#jquery #json #formatting

#jquery #json #форматирование

Вопрос:

У меня есть канал pipes jSON @ http://pipes .yahoo.com/pipes/pipe.run?_id=32188be96d1caf97c46a6fcfd8c00820amp;_render=json

 {
"count":4,
"value":{
  "title":"Copy of Twitter Farm #talkdesign Pipe",
  "description":"Pipes Output",
  "link":"http://pipes.yahoo.com/pipes/pipe.info?_id=32188be96d1caf97c46a6fcfd8c00820",
  "pubDate":"Sat, 29 Oct 2011 05:40:41 -0700",
  "generator":"http://pipes.yahoo.com/pipes/",
  "callback":"",
  "items":[
     {
        "link":"http://twitter.com/talk_design/statuses/130251640623214592",
        "description":"talk_design: Pretty cool interactive music video for Ellie Goulding's Lights! <a rel="nofollow" target="_blank" href="http://search.twitter.com/search?q=#webgl" title="#webgl" class=" ">#webgl</a> <a rel="nofollow" target="_blank" href="http://t.co/kkA3ON09">http://t.co/kkA3ON09</a>",
        "pubDate":"Sat, 29 Oct 2011 11:56:25  0000",
        "guid":"http://twitter.com/talk_design/statuses/130251640623214592",
        "author":"talk_design@twitter.com (Talk.Design)",
        "media:content":{
           "height":"48",
           "type":"image/jpg",
           "url":"http://a1.twimg.com/profile_images/1611029053/iphone-4-icon_normal.png",
           "width":"48"
        },
        "google:image_link":"http://a1.twimg.com/profile_images/1611029053/iphone-4-icon_normal.png",
        "twitter:metadata":{
           "twitter:result_type":"recent"
        },
        "y:published":{
           "hour":"11",
           "timezone":"UTC",
           "second":"25",
           "month":"10",
           "month_name":"October",
           "minute":"56",
           "utime":"1319889385",
           "day":"29",
           "day_ordinal_suffix":"th",
           "day_of_week":"6",
           "day_name":"Saturday",
           "year":"2011"
        },
        "y:id":{
           "permalink":"false",
           "value":"http://twitter.com/talk_design/statuses/130251640623214592"
        },
        "y:title":"talk_design: Pretty cool interactive music video for Ellie Goulding's Lights! #webgl http://t.co/kkA3ON09",
        "title":"We Said: Pretty cool interactive music video for Ellie Goulding's Lights! #webgl http://t.co/kkA3ON09"
     },
     {
        "link":"http://twitter.com/OwenMelbz/statuses/129989645940428800",
        "description":"OwenMelbz: @<em>talk_design</em> #<em>talk_design</em> test test test",
        "pubDate":"Fri, 28 Oct 2011 18:35:21  0000",
        "guid":"http://twitter.com/OwenMelbz/statuses/129989645940428800",
        "author":"OwenMelbz@twitter.com (Owen Melbourne)",
        "media:content":{
           "height":"48",
           "type":"image/jpg",
           "url":"http://a1.twimg.com/profile_images/702379978/DSC01872222_normal.jpg",
           "width":"48"
        },
        "google:image_link":"http://a1.twimg.com/profile_images/702379978/DSC01872222_normal.jpg",
        "twitter:metadata":{
           "twitter:result_type":"recent"
        },
        "y:published":{
           "hour":"18",
           "timezone":"UTC",
           "second":"21",
           "month":"10",
           "month_name":"October",
           "minute":"35",
           "utime":"1319826921",
           "day":"28",
           "day_ordinal_suffix":"th",
           "day_of_week":"5",
           "day_name":"Friday",
           "year":"2011"
        },
        "y:id":{
           "permalink":"false",
           "value":"http://twitter.com/OwenMelbz/statuses/129989645940428800"
        },
        "y:title":"OwenMelbz: @talk_design #talk_design test test test",
        "title":"OwenMelbz:  #talkdesign test test test"
     },
     {
        "link":"http://twitter.com/talk_design/statuses/129988795574657024",
        "description":"talk_design: Video: Jay Bradner: Open-source cancer researchFrom: TEDtalksDirector | Oct 27, 2011 | 7,265... <a rel="nofollow" target="_blank" href="http://t.co/5hrxfCHC">http://t.co/5hrxfCHC</a>",
        "pubDate":"Fri, 28 Oct 2011 18:31:58  0000",
        "guid":"http://twitter.com/talk_design/statuses/129988795574657024",
        "author":"talk_design@twitter.com (Talk.Design)",
        "media:content":{
           "height":"48",
           "type":"image/jpg",
           "url":"http://a1.twimg.com/profile_images/1611029053/iphone-4-icon_normal.png",
           "width":"48"
        },
        "google:image_link":"http://a1.twimg.com/profile_images/1611029053/iphone-4-icon_normal.png",
        "twitter:metadata":{
           "twitter:result_type":"recent"
        },
        "y:published":{
           "hour":"18",
           "timezone":"UTC",
           "second":"58",
           "month":"10",
           "month_name":"October",
           "minute":"31",
           "utime":"1319826718",
           "day":"28",
           "day_ordinal_suffix":"th",
           "day_of_week":"5",
           "day_name":"Friday",
           "year":"2011"
        },
        "y:id":{
           "permalink":"false",
           "value":"http://twitter.com/talk_design/statuses/129988795574657024"
        },
        "y:title":"talk_design: Video: Jay Bradner: Open-source cancer researchFrom: TEDtalksDirector | Oct 27, 2011 | 7,265... http://t.co/5hrxfCHC",
        "title":"We Said: Video: Jay Bradner: Open-source cancer researchFrom: TEDtalksDirector | Oct 27, 2011 | 7,265... http://t.co/5hrxfCHC"
     },
     {
        "link":"http://twitter.com/talk_design/statuses/129986263011950592",
        "description":"talk_design: setting up website and facebook :)",
        "pubDate":"Fri, 28 Oct 2011 18:21:54  0000",
        "guid":"http://twitter.com/talk_design/statuses/129986263011950592",
        "author":"talk_design@twitter.com (Talk.Design)",
        "media:content":{
           "height":"48",
           "type":"image/jpg",
           "url":"http://a1.twimg.com/profile_images/1611029053/iphone-4-icon_normal.png",
           "width":"48"
        },
        "google:image_link":"http://a1.twimg.com/profile_images/1611029053/iphone-4-icon_normal.png",
        "twitter:metadata":{
           "twitter:result_type":"recent"
        },
        "y:published":{
           "hour":"18",
           "timezone":"UTC",
           "second":"54",
           "month":"10",
           "month_name":"October",
           "minute":"21",
           "utime":"1319826114",
           "day":"28",
           "day_ordinal_suffix":"th",
           "day_of_week":"5",
           "day_name":"Friday",
           "year":"2011"
        },
        "y:id":{
           "permalink":"false",
           "value":"http://twitter.com/talk_design/statuses/129986263011950592"
        },
        "y:title":"talk_design: setting up website and facebook :)",
        "title":"We Said: setting up website and facebook :)"
     }
  ]
}
}
  

однако, хоть убей, я не могу создать свою строку, которую хочу. «теория», которую я использую, такова.

 while i <= json[count]{ //open loop using json count data
    tweet = json[items[i]][description]; //get the tweet
    tweet = tweet.replace(//g,""); //remove slashes
    by = json[items[i]][author]; //get author
    by = by.split("("); //ignore full name just get short
    by = by[1]; // shortname
    by = by.replace(/)/g,""); //remove last )
    avatar = json[items[i]][media:content][url]; //get avatar url
    avatar = avatar.replace(//g, "") //remove slashes
    tweet = "<img src="" avatar "" width="16" height="16" />" author ": " tweet; //format the tweet
    $("#tweetarea").append(tweet); //print it to #tweetarea
    i   //update counter
} //close loop
  

но, честно говоря, я не могу разобраться в этом json-жаворонке. кто-нибудь захочет написать код jquery для анализа этого json. и выполнить действия, которые я описал выше?

спасибо 🙂

Комментарии:

1. постарайтесь организовать свой вопрос в точном и аккуратном формате, который поможет вам получить ответ, сэр…

Ответ №1:

Вы можете использовать each() метод jQuery, чтобы легко перебирать JSON и добавлять конкретные данные твита к #tweetarea :

 $.each(json.value.items, function(i, tweet) {
        var author = tweet.author.split('(')[1].replace(')','');
        var avatar = tweet['media:content'].url;
        $('#tweetarea').append('<img src="' avatar '" width="16" height="16" />' author ': ' tweet['y:title'] '<br/>');
});
  

Смотрите рабочую демонстрацию

Редактировать:

Вы можете загрузить JSON с помощью ajax() метода jQuery. Вот обновленная демо-версия.

Комментарии:

1. ах, это великолепно, спасибо, однако, как мне загрузить фид в var json?

Ответ №2:

Используйте jQuery AJAX API с настройками для JSONP. Что-то вроде этого:

 $.ajax({
    url: 'yahoourlhere?callback=?'
    dataType: 'jsonp',
}).success(function(response, status, jqxhr) {

}).error(function(jqxhr, status, error) {

});
  

Вам нужно будет посмотреть, сможете ли вы получить имя обратного вызова, обернутое вокруг канала каналов. Это пример PHP того, как вы должны обернуть JSON для вызова JSONP:

 <?php
    $callback = $_REQUEST['callback'];
    echo "$callback($json)";
?>