【问题标题】:Parsing json text, then displaying it on a webpage解析 json 文本,然后将其显示在网页上
【发布时间】:2011-09-04 15:07:15
【问题描述】:

我正在与 StreamOn 合作,这是一家流媒体音频提供商,为在线广播电台分发我的音频流。他们在他们的服务器上提供当前“正在播放”的歌曲信息(他们向我提供了包含此信息的 URL)。这是我转到该 URL 时显示的数据:

{
  "interval": {
    "id": 0,
    "starts_at": 1306738563270,
"ends_at": 1306738735270
  },
  "identifier": "Music-FS680",
  "category": "music",
  "original_category": "Music",
  "buy_link": "",
  "title": "I'm That Kind of Girl",
  "artist": "Patty Loveless",
  "album": "On Down the Line",
  "publisher": "UMG Recordings, Inc.",
  "itunes_song_id": "1290089",
  "album_art": {
    "src": "http://www.streamon.fm/player/getAlbumArt.php?u=http://a6.mzstatic.com/us/r1000/016/Features/20/41/7b/dj.twfxwryv.170x170-75.jpg",
    "width": 170,
    "height": 170,
    "alt": "On Down the Line",
    "link": ""
  },
  "next_song": "Little Bitty by Alan Jackson",
  "next_buy_link": "",
  "next_album_art": {
    "src": "http://www.streamon.fm/player/getAlbumArt.php?u=http://a5.mzstatic.com/us/r1000/025/Features/b5/cb/0b/dj.frlbluta.170x170-75.jpg",
    "width": 170,
    "height": 170,
    "alt": "Everything I Love",
    "link": ""
  },
  "banner": {
    "src": "",
    "width": 0,
    "height": 0,
    "alt": "",
    "link": ""
  }
}

我需要获取该动态数据,并将其干净地显示在我的主页上,使其看起来像这样:

Title:  I'm That Kind of Girl
Artist:  Parry Loveless
Album:  On Down the Line

我知道这是文本解析,但我似乎无法弄清楚我需要使用哪种类型的文本解析方法。

【问题讨论】:

  • 您有编程语言方面的经验吗?服务器端(PHP)或客户端(javascript?)。文本是手动解析(例如您手动更新标题、艺术家和专辑)还是自动解析(例如网页应该自动检索和处理)
  • 我有一些使用 javascript 的经验。文本将需要自动解析。每次开始播放新歌曲时都会更新 JSON 数据。
  • @Luke:该文本是如何出现在您的页面上的?你能控制输出吗?如果您有服务器语言,那将是首选,因为非 JavaScript 用户也可以看到歌曲。
  • 我不太明白你在问什么。 JSON 数据在外部服务器上可用。我需要解析该数据,然后将其显示在我的网络服务器上的页面上。
  • @Luke: 托管这个包含歌曲+艺术家+专辑的网页的服务器上支持哪些编程语言?您介意发布指向该 JSON 数据的链接吗?

标签: json parsing


【解决方案1】:

那是 JSON。 http://json.org/

提供了不同语言的各种解析器

GoDaddy 支持 PHP 作为服务器端语言。一种从外部服务器解析 JSON 响应的快速而简单的方法。使用.php 扩展名(如currently_playing.php)保存以下代码:

<?php
// retrieve the contents of the URL
$ch = curl_init('http://wtsh.streamon.fm/card');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
curl_close($ch);
// parses the HTTP response and checks if the title exist
if (($json = json_decode($res)) && $json->title) {
    echo 'Title: '  . htmlspecialchars($json->title ) . '<br>';
    echo 'Artist: ' . htmlspecialchars($json->artist) . '<br>';
    echo 'Album: '  . htmlspecialchars($json->album ) . '<br>';
} else {
    echo 'No information available, please check again later';
}
?>

通常,您会对结果进行一些缓存,每 10 秒更新一次歌曲信息应该没问题。

似乎响应包含有关歌曲结束时间的数据(以毫秒为单位)。一个更好的方法是检查这个时间是否已经过去,如果是,更新缓存。

<?php // filename: current_song.php
$json = null;
$cache = 'song.json';
// if a cache exists and the time has not passed, use it
if (file_exists($cache)) {
    $json = json_decode(file_get_contents($cache));
    if ($json->interval && $json->interval->ends_at / 1000 < time()) {
        // expired, discard json
        $json = null;
    }
}
// if there is no usuable cache
if (!$json) {
    // retrieve the contents of the URL
    $ch = curl_init('http://wtsh.streamon.fm/card');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $res = curl_exec($ch);
    curl_close($ch);
    $json = json_decode($res);
    // if the title exists, assume the result to be valid
    if ($json && $json->title) {
        // cache it
        $fp = fopen('song.json', 'w');
        fwrite($fp, $res);
        fclose($fp);
    } else {
        $json = null;
    }
}
if ($json) {
    $info = array();
    // contains the time in milliseconds
    $info['wait_ms'] = $json->interval->ends_at - 1000 * microtime(true);
    $info['title']   = $json->title ;
    $info['artist']  = $json->artist;
    $info['album']   = $json->album ;
    $info['image']   = $json->album_art;
    // display a JSON response for the HTML page
    echo json_encode($info);
}
?>

要将其嵌入 HTML 页面,请使用:

<img id="song_image"><br>
Title:  <span id="song_title">-</span><br>
Artist: <span id="song_artist">-</span><br>
Album:  <span id="song_album">-</span>
<script>
(function () {
    // we need a JSON parser, if it does not exist, load it
    if (typeof JSON == "undefined") {
        var s = document.createElement("script");
        // json2.js retrieved from https://github.com/douglascrockford/JSON-js
        s.src = "json2.js";
        document.getElementsByTagName("head").appendChild(s);
    }
})();
var song_ends = 0;
function update_song () {
    if ((new Date).getTime() < song_ends) {
        // use cached result as the song has not ended yet
        return;
    }
    var req = new XMLHttpRequest();
    // IE compatbility:
    var textContent = 'textContent' in document ? 'textContent' : 'innerText';
    req.onreadystatechange = function () {
        if (req.readyState == 4) {
            var song = JSON.parse(req.responseText);
            if (song.title) {
                var img = document.getElementById("song_image");
                img.alt = song.image.alt;
                img.src = song.image.src;
                img.width = song.image.width;
                img.height = song.image.height;
                document.getElementById("song_title")[textContent]  = song.title ;
                document.getElementById("song_artist")[textContent] = song.artist;
                document.getElementById("song_album")[textContent]  = song.album ;
                // store the end date in javascript date format
                song_ends = (new Date).getTime() + song.wait_ms;
            }
        }
    };
    req.open('get', 'current_song.php', true);
    req.send(null);
}
// poll for changes every second
setInterval(update_song, 1000);
// and update the song information
update_song();
</script>

【讨论】:

  • 效果很好!如何设置自动 10 秒更新?
  • 想出了如何将其嵌入到 html 页面中......这是一个愚蠢的问题。感谢您提供有关更新的信息!还有一个问题,我会让你一个人呆着。 JSON 数据包括专辑封面图像的 URL。我如何在代码中得到它,以便专辑封面显示在文本信息旁边?
  • @Lekensteyn:当我将该代码粘贴到我的 html 页面的正文部分时,显示的只是此页面上的以下文本:lbrannonent.com/test.html
  • @luke:哎呀,我在里面放了一个多余的标签。你能发现吗? :)
  • @Lekensteyn:啊,是的,额外的 标签。它仍然无法正常工作。我在lbrannonent.com/test.html 用新代码更新了它
【解决方案2】:

这是 JSON 解析,而不是文本解析。根据您用于解码该 JSON 的语言,您可以使用一些现成的函数以非常直接和简单的方式获取您想要的值。

在 PHP 中,您可以使用 json_decode 函数

在 javascript 中,json 是原生的,请参阅here 如何访问您的数据成员

【讨论】:

  • 你能推荐一个好的 JSON 解析器吗?我只需要在 html 页面上显示解析后的数据。
猜你喜欢
  • 1970-01-01
  • 2013-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多