Posts Tagged ‘JSON’
Posted in 'JavaScript' by James on October 17th, 2009
The following quote is derived from an expert recommended book that covers the many aspects of Ajax. It’s called “Ajax in Action”, authored by Dave Crane, Eric Pascarello, and Darren James.
“The JavaScript Object Notation (JSON) is a core feature of the language [JavaScript]. It provides a concise mechanism for creating arrays and object graphs. In order to understand JSON, we need to know how JavaScript arrays work [...]”
Hopefully you’ve spotted the dodgy parts of that quote. For one, JSON, the data-interchange format is not actually a core feature of JavaScript and is, in more ways that one, quite different to JavaScript’s object notation (i.e. the way you markup an object literal in JavaScript code).
Despite my dismay I continued to read onwards, and I can tell you that the author has also made the classic mistake of thinking that JavaScript supports associative arrays, and for some reason thinks that you have to understand JavaScript arrays in order to understand JSON… (???)
So, just to set the record straight, JSON is an interchange format created/coined by Doug Crockford. It’s a subset of JavaScript’s object notation (specified in the ECMA-262 specification). To prove this, here’s a valid JavaScript object literal:
Yes, I know, on its own it’s not valid JavaScript (since it’s interpreted as a compound statement), but that doesn’t matter; it is a valid object literal.
Run that through a JSON validator and you’ll get errors. That’s because JSON is not the same as JavaScript’s object notation. To make the above code a valid piece of JSON you’d have to wrap each property name (e.g. foo) with double quotes:
{
"foo": 123,
"bar": 456
}
I don’t blame the author of that book. In all likelihood, the information within that book was thought of as 100% correct at the time of writing. I only wanted to set-straight one of many misconceptions surrounding JavaScript and its “subsets”.
PS. Please forgive the confusing title.
Posted in 'Code Snippets, JavaScript' by James on March 21st, 2009
I’ve recently been checking out YQL, Yahoo’s new gift to developers! The idea behind it is to unify the complicated world of APIs into one solid SQL-like abstraction; flickr feeds, search, weather and RSS feeds (etc). Additionally, it can retrieve HTML, XML, CSV, ATOM and more, all returned as structured data via either the JSON or XML format.
The fact that it has the capability to return JSON and even JSONP means cross-domain web querying is now a piece of cake. Just imagine being able to have access to the entire internet from the comfort of the client-side!
If you have a Yahoo account you should definitely check out the console; there’s a bunch of examples to choose from on the side. Try this query:
SELECT * FROM html WHERE url='http://news.bbc.co.uk' AND xpath="//*[@id='livestats200']//ul[contains(@class,'popstoryList')]/li/a" LIMIT 1
The above query should return the most read article on the BBC website (at the time of querying). You can use XPATH to retrieve specific nodes within the targetted document. It would be cool if YQL supported CSS selectors as many more people know the syntax but unfortunately we’re stuck with XPATH… It’s not too hard to learn though, if you’re new to it then this page is worth a glance: http://www.w3schools.com/XPath/xpath_syntax.asp.
I’ve started development on a “CSS to XPATH” converter for JavaScript, it works quite well, but it’s not quite robust enough to deal with complicated selectors yet.
I’ve also written a small interface for working with YQL within your JavaScript applications (framework agnostic). Have a look:
// YQL serves JSONP (with a callback) so all we have to do
// is create a script element with the right 'src':
function YQLQuery(query, callback) {
this.query = query;
this.callback = callback || function(){};
this.fetch = function() {
if (!this.query || !this.callback) {
throw new Error('YQLQuery.fetch(): Parameters may be undefined');
}
var scriptEl = document.createElement('script'),
uid = 'yql' + +new Date(),
encodedQuery = encodeURIComponent(this.query.toLowerCase()),
instance = this;
YQLQuery[uid] = function(json) {
instance.callback(json);
delete YQLQuery[uid];
document.body.removeChild(scriptEl);
};
scriptEl.src = 'http://query.yahooapis.com/v1/public/yql?q='
+ encodedQuery + '&format=json&callback=YQLQuery.' + uid;
document.body.appendChild(scriptEl);
};
}
Use it like this:
// Alert the latest post title from Ajaxian.com
// Construct your query:
var query = "select * from rss where url='feeds2.feedburner.com/ajaxian' limit 1";
// Define your callback:
var callback = function(data) {
var post = data.query.results.item;
alert(post.title);
};
// Instantiate with the query:
var ajaxianPosts = new YQLQuery(query, callback);
// If you're ready then go:
ajaxianPosts.fetch(); // Go!!
/* Callback & query can be defined as properties also:
ajaxianPosts.query = 'select * from...';
ajaxianPosts.callback = function(){}; */
Also, for you jQuery junkies, here’s a plugin:
$.YQL = function(query, callback) {
if (!query || !callback) {
throw new Error('$.YQL(): Parameters may be undefined');
}
var encodedQuery = encodeURIComponent(query.toLowerCase()),
url = 'http://query.yahooapis.com/v1/public/yql?q='
+ encodedQuery + '&format=json&callback=?';
$.getJSON(url, callback);
};
// Usage:
$.YQL("select * from rss where url='feeds2.feedburner.com/ajaxian' limit 1", function(data) {
var post = data.query.results.item;
alert(post.title);
});
Even if you’re not planning on using it in a project it’s definitely worth a look and Yahoo’s console makes it incredibly easy to play around with it.
Posted in 'Code Snippets, JavaScript, PHP' by James on January 7th, 2009
Here’s a very handy script which will scan through a directory of images, form an array of the contents of that directory and then return the array in JSON format to the client-side where the images will be preloaded into the user’s cache.
There are two components to this: the PHP script and some simple JavaScript:
Posted in 'JavaScript' by James on December 24th, 2008
To Mr. Joe Average web developer JSON may just seem like yet another pointless buzzword but to the enquiring mind it is so much more!
For me, the opportunities JSON presents are much more appreciated when looking at JSONP, a slight variation which stands for ‘JavaScript Object Notation with Padding‘. They both essentially refer to the same thing but just to clear, there is a difference:
// JSON:
{
'name' : 'john',
'age' : 23,
'hobbies' : ['football','cooking','rock climbing'],
'temper' : 'moody'
}
// JSONP:
newPerson({
'name' : 'john',
'age' : 23,
'hobbies' : ['football','cooking','rock climbing'],
'temper' : 'moody'
});
As you can see, the only difference is that JSONP format requires some type of callback function with the object passed as a parameter whereas regular JSON is just a regular inline JavaScript object (the theory behind JSONP is that the callback name is specified by the requester (within the query string), not by the party which receives the request).