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.