Luke
Luke

Reputation: 37

Parsing json text, then displaying it on a webpage

I am working with StreamOn, a streaming audio provider to distribute my audio stream for an online radio station. They make current "now playing" song information available on their servers (they provide me with the URL containing this information). Here is the data that is displayed when I go to that 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": ""
  }
}

I need to take that dynamic data, and cleanly display it on my homepage so that it looks like this:

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

I know this is text parsing, but I can't seem to figure out what type of text parsing method I need to use.

Upvotes: 1

Views: 7564

Answers (2)

Lekensteyn
Lekensteyn

Reputation: 66435

That's JSON. Various parsers for different languages are available at http://json.org/

GoDaddy supports PHP as server-side language. A quick-and-dirty way to get parse the JSON response from an external server. Save the below code with a .php extension (like 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';
}
?>

Usually, you would do some caching of the result, updating the song information every 10 seconds should be fine.

It appears that the response contains data on the end time of the song (in milliseconds). A better approach would then be checking if this time has passed, and if so, update the cache.

<?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);
}
?>

To embed it in a HTML page, use:

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

Upvotes: 2

Tudor Constantin
Tudor Constantin

Reputation: 26861

This is JSON parsing, not text parsing. Depending on the language you use to decode that JSON, you could use some ready made functions to obtain the values you want in a very straight forward and easy way.

In PHP, you could use the json_decode function

In javascript, json is native, see here how to access your data members

Upvotes: 2

Related Questions