Continuing from last time, this post discusses the real-world use of JSON in brief form.
We could then incorporate it like any other external JavaScript, using:
In fact we could use a .json or even a .txt extension for our file and it would still work. Try it by saving the object code to a file called myjsonfile.txt and in the same folder save this file as HTML:
Try changing your source file to this new text and you'll be left with a sad face when you load it into the browser because nothing will appear.
There's a lot of stuff going on in a small space here, so let's explain what's happened:
This uses the expanded $.ajax function to make it compatible across browsers, and I have to thank here Damien du Toit's query.twitter.js project for pointers on how to resolve cross-browser incompatibilities.
You'll also notice instead of using document.write this code uses a paragraph with an id, which the jQuery then uses to place the generated code output within.
It might look a bit overwhelming with the callbackParameter and the jsonp, but these are things to become familiar with if you are looking to use JSON and I'd recommend you take the time to look them up.
Update: following the retirement of Twitter's v1.0 API in favour of v1.1 this code no longer works, since all access (from June 2013) now requires authentication.
Note: you are restricted to 150 calls per hour, so beware using HTML editors that have live previews.
Let's get started
Things would be simple if JSON was always available to our code as an object, i.e. if we had an external file saved with a .js extension that read:
var object = {
"type":"car",
"colours":["red","green", "purple", "white"],
"trim":{"racer":"leather","ambler":"suede", "skate":"plastic"},
"number":100};
We could then incorporate it like any other external JavaScript, using:
<script src="myjsonfile.js"></script>
In fact we could use a .json or even a .txt extension for our file and it would still work. Try it by saving the object code to a file called myjsonfile.txt and in the same folder save this file as HTML:
<!DOCTYPE html>
<html>
<head><script src="myjsonfile.txt"></script></head>
<body>
<script>
document.write("I'd like a "+object.type+" in "+object.colours[1]+" with "+object.trim['skate']+" trim");
</script>
</body>
</html>
<html>
<head><script src="myjsonfile.txt"></script></head>
<body>
<script>
document.write("I'd like a "+object.type+" in "+object.colours[1]+" with "+object.trim['skate']+" trim");
</script>
</body>
</html>
The truth
Real life isn't like that. Normally what we'll be faced with is a plain text file or more likely a page of JSON rendered in the browser as the result of a query posted to a server. So our JSON will actually look like this:
{"type":"car",
"colours":["red","green", "purple", "white"],
"trim":{"racer":"leather","ambler":"suede", "skate":"plastic"},
"number":100};
Try changing your source file to this new text and you'll be left with a sad face when you load it into the browser because nothing will appear.
Tell me what to do
Modern browsers allow you to use a JavaScript function called JSON.parse but its implementation isn't that recent (see here for browsers with support for it), and we are also left with the messy business of opening the text file in the first place or retrieving the text online when working with JavaScript in the raw.
This makes an ideal opportunity to use our jQuery knowledge and a function called $.getJSON:
This makes an ideal opportunity to use our jQuery knowledge and a function called $.getJSON:
<!DOCTYPE html>
<html>
<head><script src="http://code.jquery.com/jquery-latest.js"></script></head>
<body>
<script>
$.getJSON('myjsonfile.txt', function(object) {
document.write("I'd like a "+object.type+" in "+object.colours[1]+" with "+object.trim['skate']+" trim");
});
</script>
</body>
</html>
<html>
<head><script src="http://code.jquery.com/jquery-latest.js"></script></head>
<body>
<script>
$.getJSON('myjsonfile.txt', function(object) {
document.write("I'd like a "+object.type+" in "+object.colours[1]+" with "+object.trim['skate']+" trim");
});
</script>
</body>
</html>
There's a lot of stuff going on in a small space here, so let's explain what's happened:
- We've used $.getJSON to obtain the contents of the file - 'myjsonfile.txt'
- The contents of this file (our JSON) is passed to the function that follows the filename after the comma
- This piece of jQuery does everything we need to turn the JSON text into a proper object and it is now possible to access the values contained in the JSON as we did in the previous post
What if our data was online (somewhere like Twitter, for example)?
This starts to push us into more complex areas but for completeness of this overview let's now adapt the code for receiving the latest tweet from the @sketchyTech feed:
<!DOCTYPE html>
<html>
<head><script src="http://code.jquery.com/jquery-latest.js"></script></head>
<body>
<p id="para"></para>
<script>
$.ajax({
url: "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=sketchytech&include_rts=1",
data: {},
dataType: "jsonp",
callbackParameter: "callback",
timeout: 5000,
success: function(data) {
var a = "<b>Latest Tweet from <a href='http://twitter.com/sketchytech'>@sketchyTech</a>:</b> " +data[0].text;
$("#para").html(a);
}
});
</body>
</html>
<html>
<head><script src="http://code.jquery.com/jquery-latest.js"></script></head>
<body>
<p id="para"></para>
<script>
$.ajax({
url: "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=sketchytech&include_rts=1",
data: {},
dataType: "jsonp",
callbackParameter: "callback",
timeout: 5000,
success: function(data) {
var a = "<b>Latest Tweet from <a href='http://twitter.com/sketchytech'>@sketchyTech</a>:</b> " +data[0].text;
$("#para").html(a);
}
});
</script>
</body>
</html>
This uses the expanded $.ajax function to make it compatible across browsers, and I have to thank here Damien du Toit's query.twitter.js project for pointers on how to resolve cross-browser incompatibilities.
You'll also notice instead of using document.write this code uses a paragraph with an id, which the jQuery then uses to place the generated code output within.
It might look a bit overwhelming with the callbackParameter and the jsonp, but these are things to become familiar with if you are looking to use JSON and I'd recommend you take the time to look them up.
Update: following the retirement of Twitter's v1.0 API in favour of v1.1 this code no longer works, since all access (from June 2013) now requires authentication.
What's next?
First, copy and paste that last piece of code into an HTML document and try it out. Next, experiment retrieving JSON from your own twitter stream (or elsewhere).Note: you are restricted to 150 calls per hour, so beware using HTML editors that have live previews.
Comments
Post a Comment