Кто-нибудь скажет мне, как получить атрибут media: thumb для фида json? - PullRequest
0 голосов
/ 03 апреля 2010

Я сделал трубу Yahoo, которая вытягивает атомы в формате json; однако я могу получить и отобразить все элементы на моей html-странице, кроме атрибута элемента.

Кто-нибудь скажет мне, как получить атрибут media: thumb для фида json?

Я вставляю код html-страницы в javascript. Если вы сохраните html-страницу и затем просмотрите ее в браузере, вы увидите, что на html-странице выводятся все необходимые элементы, кроме media: thumb, поскольку я не могу отобразить атрибут media: thumb, когда канал отформатирован как json.

Я также вставляю некоторую часть фида json, чтобы вы могли понять, о чем я говорю.

Скажите, пожалуйста, как получить атрибут с носителя: элемент thumb в фиде json, используя обычный javascript, но без кода на стороне сервера или библиотеки javascript.

Спасибо.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <script type="text/javascript">
    function getFeed(feed){
    var newScript = document.createElement('script');
    newScript.type = 'text/javascript';
    newScript.src = 'http://pipes.yahoo.com/pipes/pipe.run?_id=40616620df99780bceb3fe923cecd216&_render=json&_callback=piper';
document.getElementsByTagName("head")[0].appendChild(newScript);
    }
    function piper(feed){
var tmp='';
            for (var i=0; i<feed.value.items.length; i++) {
            tmp+='<a href="'+feed.value.items[i].link+'">';
            tmp+=feed.value.items[i].title+'</a><br>';
            tmp+=feed.value.items[i].author.name+'<br>';
            tmp+=feed.value.items[i].published+'<br><br>';
            if (feed.value.items[i].description) {
                tmp+=feed.value.items[i].description+'<br>';

            }
            tmp+='<hr>';
            }
            document.getElementById('rssLayer').innerHTML=tmp;
    }

    </script>
</head>
<body onload="getFeed('http://del.icio.us/rss/popular/javascript')">
    <div id='rssLayer'>bchnbc</div>
</body>
</html>

Некоторая часть фида json, генерируемая каналом Yahoo:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
</head>
piper({"count":2,"value":{"title":"myPipe","description":"Pipes Output","link":"http:\/\/pipes.yahoo.com\/pipes\/pipe.info?_id=f7f4175d493cf1171aecbd3268fea5ee","pubDate":"Fri, 02 Apr 2010 17:59:22 -0700","generator":"http:\/\/pipes.yahoo.com\/pipes\/","callback":"piper",


"items":

[{

"rights":"Attribution - Noncommercial - No Derivative Works",
"link":"http:\/\/vodo.net\/mixtape1",
"y:id":{"value":null,"permalink":"true"},
"content":{"content":"We're proud to be releasing this first VODO MIXTAPE. Actual tape might be a thing of the past, but before P2P, mixtapes were the most popular way of sharing popular culture the world had known -- and once called the 'most widely practiced American art form'. We want to resuscitate the spirit of the mixtape for this VODO MIXTAPE series: compilations of our favourite shorts, the weird, the wild and the wonky, all brought together in a temporary and uncomfortable company.","type":"text"},

"author":
{"name":"Various"},
"description":"We're proud to be releasing this first VODO MIXTAPE. Actual tape might be a thing of the past, but before P2P, mixtapes were the
most popular way of sharing popular culture the world had known -- and once called the 'most widely practiced American art form'. We want to resuscitate the spirit
of the mixtape for this VODO MIXTAPE series: compilations of our favourite shorts, the weird, the wild and the wonky, all brought together in a temporary and
uncomfortable company.",
"media:thumbnail":
{
"url":"http:\/\/vodo.net\/\/thumbnails\/Mixtape1.jpg"
},
"published":"2010-03-08-09:20:20 PM",
"format":
{
"audio_bitrate":null,
"width":"608",
"xmlns":"http:\/\/xmlns.transmission.cc\/FileFormat",
"channels":"2",
"samplerate":"44100.0",
"duration":"3092.36",
"height":"352",
"size":"733925376.0",
"framerate":"25.0",
"audio_codec":"mp3",
"video_bitrate":"1898.0",
"video_codec":"XVID",
"pixel_aspect_ratio":"16:9"
},
"y:title":"Mixtape #1: VODO's favourite short films",
"title":"Mixtape #1: VODO's favourite short films",
"id":null,
"pubDate":"2010-03-08-09:20:20 PM",
"y:published":{"hour":"3","timezone":"UTC","second":"0","month":"4","minute":"10","utime":"1270264200","day":"3","day_of_week":"6","year":"2010"
}},


{"rights":"Attribution - Noncommercial - No Derivative Works","link":"http:\/\/vodo.net\/gilbert","y:id":{"value":"cd6584e06ea4ce7fcd34172f4bbd919e295f8680","permalink":"true"},"content":{"content":"A documentary short about Gilbert, the Beacon Hill \"town crier.\" For the last 9 years, since losing his job and becoming homeless, Gilbert has delivered the weather, sports, and breaking headlines from his spot on the Boston Common. Music (used with permission) in this piece is called \"Blue Bicycle\" by Dusseldorf-based pianist \/ composer Volker Bertelmann also known as Hauschka. Artistic Statement: This is the first in a series of profiles of people who I think are interesting, and who I see on almost a daily basis. I don't want to limit the series to people who live \"on the fringe,\" but it would be appropriate to say that most of the people I interview are eclectic, eccentric, and just a little bit unique. The art is in the viewing - but I hope to turn my lens on individuals that don't always color in the lines, whether they can help it or not.","type":"text"},"author":{"name":"Nathaniel Hansen"},"description":"A documentary short about Gilbert, the Beacon Hill \"town crier.\" For the last 9 years, since losing his job and becoming homeless, Gilbert has delivered the weather, sports, and breaking headlines from his spot on the Boston Common. Music (used with permission) in this piece is called \"Blue Bicycle\" by Dusseldorf-based pianist \/ composer Volker Bertelmann also known as Hauschka. Artistic Statement: This is the first in a series of profiles of people who I think are interesting, and who I see on almost a daily basis. I don't want to limit the series to people who live \"on the fringe,\" but it would be appropriate to say that most of the people I interview are eclectic, eccentric, and just a little bit unique. The art is in the viewing - but I hope to turn my lens on individuals that don't always color in the lines, whether they can help it or not.","media:thumbnail":{"url":"http:\/\/vodo.net\/\/thumbnails\/gilbert.jpeg"},"published":"2010-03-03-10:37:05 AM","format":{"audio_bitrate":null,"width":"624","xmlns":"http:\/\/xmlns.transmission.cc\/FileFormat","channels":"2","samplerate":null,"duration":"373.673","height":"352","size":"123321266.0","framerate":null,"audio_codec":"mp3","video_bitrate":null,"video_codec":"XVID","pixel_aspect_ratio":"16:9"},"y:title":"Gilbert","title":"Gilbert","id":"cd6584e06ea4ce7fcd34172f4bbd919e295f8680","pubDate":"2010-03-03-10:37:05 AM","y:published":{"hour":"3","timezone":"UTC","second":"0","month":"4","minute":"10","utime":"1270264200","day":"3","day_of_week":"6","year":"2010"
}}

]
}})

Ответы [ 2 ]

0 голосов
/ 05 апреля 2010

Проходить документы XML намного проще, чем обходить объекты JSON, чтобы найти конкретный тип узла. В XML это будет так же просто, как xmlDom.getElementsByTagName ("media: thumb").

Тем не менее, в Javascript, я пошел на следующее:

function recurseAndFind(obj, key) {
  var x,
      temp,
      current,
      ret = [];

  for (x in obj) {
    if (obj.hasOwnProperty(x)) {
      current = obj[x];

      if (x == key) {
        ret.push(current);
      } else if (typeof current === "object") {
        temp = recurseAndFind(current, key);

        if (temp.length) {
          ret = ret.concat(temp);
        };
      } else if (typeof current === "array") {
        for (var i=0;i<current.length;i++) {
          temp = recurseAndFind(current[i], key);

          if (temp.length) {
            ret = ret.concat(temp);
          };
        };
      };
    };
  };

  return ret;
};

Что используется следующим образом:

var allOccurancesOfMediaThumb = recurseAndFind(items, 'media:thumb');

allOccurancesOfMediaThumb будет массивом вхождений (или пустым массивом, если ничего не найдено).

0 голосов
/ 05 апреля 2010

Если вы создали JSON, не можете ли вы отредактировать ленту, чтобы отобразить элементы, которыми вы можете манипулировать с помощью javascript?

...