[Beginner] Basic Twitch website integration

JSON is like an extension of JavaScript; it’s is just a JavaScript compatible format for sending data, and if you’re writing in JavaScript the basic functions are built in. It encodes the data in almost the same way you do when writing JavaScript code, which makes it very easy to both read and create it with JavaScript programs.

Encode it with JSON.stringify() and decode it with JSON.parse().

You’ve heard of XML, right? Well JSON is just the next evolution that everyone’s adapted to for sharing data between software.

This should help clarify things:
this array of data
{1: "one", 2: "two", ["three", "four"]}
or written as
{"1":"one","2":"two",["three","four"]}
would encoded to
{"1":"one","2":"two",["three","four"]}
in JSON format.

And if you’re using jQuery, as a simple example:
$.getJSON('https://api.twitch.tv/kraken/streams/lirik?callback=?').done(function(data){console.log(data.stream?'LIVE NOW':'OFFLINE')})
will print ‘LIVE NOW’ or ‘OFFLINE’ for lirik’s stream (you can paste it into your browser’s JavaScript console to see it work).

And if you want to get around your browser’s cross-site-scripting limitations, you use a callback as above. If you’re on the same domain, or running the code outside of a browser, or just want to open the JSON URL in your browser to view the data, you don’t need the callback (as a callback WILL change the data you get back; the server will wrap it in a function). To see a live example you can just click the following URL, it should help you understand what you’re checking for:
https://api.twitch.tv/kraken/streams/lirik

So if you want to check the channel status every minute, you could imagine using client-side JavaScript to check once on load and then again every minute on a timer after that; then updating the image / text with jQuery the first time plus whenever it changes.

–OR–

If you wanted to go the PHP route, just poll the same API (no callback, like in the above link), decode as JSON (the function’s built into PHP as well), and check if object stream is null or not. If it’s null, show the offline image / text; otherwise, show the online image / text.

I’m really not good with PHP (nor do I take credit for writing this), so this probably isn’t very clean, but:
`<?php
$channel = “swifty”;
$json_file = @file_get_contents(“https://api.twitch.tv/kraken/streams/{$channel}”, 0, null, null);
$json_array = json_decode($json_file, true);
if ($json_array[‘stream’] == null)
{ ?>
OFFLINE

<?php } else { ?>

ONLINE

<?php } ?>`

You might not want all that right in the body, so feel free to clean things up if you don’t, but the basics are all there and it’s a working example.

1 Like