解析json文本,然后在网页上显示它

时间:2011-05-30 07:29:29

标签: json parsing

我正在与流媒体音频提供商StreamOn合作,为在线广播电台分发我的音频流。他们在他们的服务器上提供当前“正在播放”的歌曲信息(它们为我提供了包含此信息的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

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

2 个答案:

答案 0 :(得分:2)

这是JSON解析,而不是文本解析。根据您用来解码JSON的语言,您可以使用一些现成的函数以非常简单的方式获得所需的值。

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

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

答案 1 :(得分:2)

那是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>