Activate your free membership today | Log-in

Tuesday, April 22nd, 2008

Google offers Search, Feed, and Translation APIs to Non Ajax Usage

Category: JavaScript, Library, Google, JSON

The Google Ajax API team has been offering great services that you can use from JavaScript in the browser. I have talked about some of them on Ajaxian before (Feed API, Feed Discovery API, and the recent Language API) but now we have a great new release that enables you to access these APIs from Flash or the server side.

In fact, as long as your program can speak HTTP, you can have access to the services.

For example, you could now call this an REST API to Google Search.

To see it in action, point to something like http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Ajaxian and you will see the JSON output that is documented.

There are terms of use that you should abide by, and some other comments:

An area to pay special attention to relates to correctly identifying
yourself in your requests. Applications MUST always include a valid and accurate http referer header in their requests. In addition, we ask, but do not require, that each request contains a valid API Key. By providing a key, your application provides us with a secondary identification mechanism that is useful should we need to contact you in order to correct any problems.

Check out the updated documentation for more details on each API:

Including code snippets. For example, here is how you would access the search results in ActionScript:

JAVASCRIPT:
  1.  
  2. var service:HTTPService = new HTTPService();
  3. service.url = 'http://ajax.googleapis.com/ajax/services/search/web';
  4. service.request.v = '1.0';
  5. service.request.q = 'Paris Hilton';
  6. service.resultFormat = 'text';
  7. service.addEventListener(ResultEvent.RESULT, onServerResponse);
  8. service.send();
  9.  
  10. private function onServerResponse(event:ResultEvent):void {
  11.   try {
  12.     var json:Object = JSON.decode(event.result as String);
  13.     // now have some fun with the results...
  14.   } catch(ignored:Error) {
  15.   }
  16. }
  17.  

If you are interested in this kind of thing, as well as Gears, OpenSocial, AppEngine, or Android, check out the Google Developer Days coming to cities around the world or our big Google I/O event on May 28-29 in San Francisco.

Posted by Dion Almaer at 9:07 am
2 Comments

++++-
4.7 rating from 16 votes

Monday, April 21st, 2008

JSONVid: Pure JavaScript Video Player

Category: JavaScript, Library, Examples, JSON

Jacob Seidelin went on a ( crazy :) ) mission to create a pure JavaScript video player that didn't use Flash:

My first thought was to read binary video files using a technique like the Andy Na posted about here, figuring that there must be some really simple to parse video formats around, but I soon changed directions and decided to make up a whole new video format. Enter.. JSONVid. Using a player like mplayer, it is easy to export all frames in a movie clip to individual jpeg files, and using whichever language you prefer it is also fairly trivial to collect these files, base64 encode the bunch of them and throw them all together in a nice JSON file (I used this PHP script).

The format uses good ole data: URLs, which are finally supported in IE with version 8:

JSON:

    {
      frm : "JSVID",   // format id tag
      ver : 1,  // version number of format
      width : 320,  // width of video
      height : 240,  // height of video
      rate : 15,  // framerate (frames per second)
      frames : 495,  // number of frames in file
      data : {
        video : [ // here comes 495 data:uris containing base64 encoded jpeg image frames
          "data:image/jpeg;base64,/9j/4AAQSkZJRgABAgEASABIAAD/7gAOQWRv ... ",
          "data:image/jpeg;base64,/9j/4AAQSkZJRgABAgEASABIAAD/7gAOQWRv ... ",
          ...
        ]
      }
    }

Then he created the player:

First strategy was to create an Image object for each frame and render it on a canvas element using drawImage(). That worked fine and performance was nice (although Opera used a lot of CPU), but I figured I'd try just using a regular image tag and just change the src property to another data:uri each frame. The change was barely noticeably in Firefox and Safari and it ran a bit better in Opera, so I lost the canvas and stuck with plain old images.

Now, it seems that Firefox will eat up all the memory in the world if you keep throwing new data:uris at the same image tag, which led to another change, so for each frame a new Image object was created and saved for later and as the video played, the previous frame Image was replaced by the new Image object. That seemed to work, but introduced an annoying delay as all these Image objects were created before playing, so I ended up moving the Image creation to actual render cycle where it simply checks if the frame Image has already been created, and if not, creates it.

You can now get going with HTML such as:

HTML:
  1.  
  2. <script src="jsvideo.js" type="text/javascript"></script>
  3. </head>
  4. <div videosrc="myvideo.jsvid" videoautoplay="true"></div>
  5. </body>
  6. </html>
  7.  

There are a couple of tests to play with. It was also pointed out that maybe an animated gif/png would be a choice (without controls), and of course, Flash is still the best choice here, until we get video support in most browsers.

Posted by Dion Almaer at 9:15 am
10 Comments

+++--
3.6 rating from 37 votes

Friday, April 18th, 2008

Conform your JSON to ECMAScript 4 with JCON

Category: Library, JSON

Oliver Steele is doing great work, and he has just released a gem called JCON which stands for JavaScript Conformance. It tests JSON values to make sure that they are valid for the new world of ECMAScript 4 type definitions (e.g. new { x:int, y:string }( 3, "foo" ) ).

Usage

RUBY:
    type = JCON::parse "[string, int]"
    type.contains?([‘a’, 1])     # => true
    type.contains?([‘a’, ‘b’])   # => false
    type.contains?([‘a’, 1, 2])  # => true

    // via RSpec
    [1, ‘xyzzy’].should conform_to_js(‘[int, string]’)
    [1, 2, ‘xyzzy’].should_not conform_to_js(‘[int, string]’)  # 2 isn’t a string
    {:x => 1}.should conform_to_js(‘{x: int}’)

    // with JavaScript Fu
    # this will succeed if e.g. response contains a script tag that includes
    #   fn("id", {x:1, y:2}, true)
    response.should call_js(‘fn’) do |args|
      args[0].should conform_to_js(‘string’)
      args[1].should conform_to_js(‘{x:int, y:int}’)
      args[2].should conform_to_js(‘boolean’)
      # or:
      args.should conform_to_js(‘[string, {x:int, y:int}, boolean]’)
    end

In other JSON news, it appears that new ECMAScript standard will no longer reserve the words:

abstract boolean byte char double final float implements int interface
long native package private protected public short static synchronized
throws transient volatile

And Douglas Crockford says that no browsers reserve them, and thus he is unreserving them from jsLint.

Posted by Dion Almaer at 5:50 am
1 Comment

+++--
3 rating from 4 votes

Thursday, March 20th, 2008

SMD: Pluggable Web Services

Category: JavaScript, Library, Dojo, JSON

JAVASCRIPT:
  1.  
  2. {target:"/jsonrpc", // this defines the URL to connect for the services
  3.  transport:"POST", // We will use POST as the transport
  4.  envelope:"JSON-RPC-1.2", // We will use JSON-RPC
  5.  SMDVersion:"2.0",
  6.  services: {
  7.    add : { // define a service to add two numbers
  8.    parameters: [
  9.      {name:"a",type:"number"}, // define the two parameters
  10.      {name:"b",type:"number"}],
  11.    returns:{"type":"number"}
  12.  },
  13.  foo : {   // nothing is required to be defined, all definitions are optional.
  14.    //This service has nothing defined so it can take any parameters
  15.   //and return any value
  16.  },
  17.  getNews : {
  18.    // we can redefine the target, transport, and envelope for specific services
  19.    target: "/newsSearch",
  20.    transport: "GET",
  21.    envelope: "URL",
  22.    parameters:[ { name: "query", type: "string", optional: false, default: "" } ],
  23.    returns:{type:"array"}
  24.  }
  25. }
  26.  

What is that? Does it look a little WSDL-y without the XML? This format is Service Mapping Description (SMD), and Kris Zyp talks about how it enables pluggable Web services.

With the schema about you can wire it together (example using Dojo):

JAVASCRIPT:
  1.  
  2. var services = new dojox.rpc.Service("http://mydomain.com/mySMD");
  3.  
  4. var newsDeferred = services.getNews({query:"dojo"});
  5. newsDeferred.addCallback(function(returnValue) {
  6.     alert("A news item: " + returnValue[0]);
  7. });
  8.  

Neil Roberts asked about cross domain SMDs and Kris said:

Yes, we will use JSONP, although we use a special form, where the callback function will be derived directly from the name of the SMD, in order to allow for static creation of SMDs that can be accessed cross-domain.

Posted by Dion Almaer at 7:46 am
Comment here

++++-
4.5 rating from 19 votes

Monday, March 3rd, 2008

Json.NET 2.0

Category: .NET, JSON

James Newton-King has quickly released a new version of Json.NET that has a new easier syntax for querying and and creating JSON.

Creating JSON

JAVASCRIPT:
  1.  
  2. JObject o = JObject.FromObject(new
  3. {
  4.   channel = new
  5.   {
  6.     title = "James Newton-King",
  7.     link = "http://james.newtonking.com",
  8.     description = "James Newton-King's blog.",
  9.     item =
  10.         from p in posts
  11.         orderby p.Title
  12.         select new
  13.         {
  14.           title = p.Title,
  15.           description = p.Description,
  16.           link = p.Link,
  17.           category = p.Categories
  18.         }
  19.   }
  20. });
  21.  

Querying JSON

JAVASCRIPT:
  1.  
  2. var categories =
  3.   from c in rss["channel"]["item"].Children()["category"].Values<string>()
  4.   group c by c into g
  5.   orderby g.Count() descending
  6.   select new { Category = g.Key, Count = g.Count() };
  7.  

Check out the project.

Posted by Dion Almaer at 6:11 am
5 Comments

+++--
3.2 rating from 17 votes

Wednesday, February 20th, 2008

YUI 2.5 released - Layout Manager, File Uploader and graphical JavaScript Profiler - and that is just the start

Category: JavaScript, Library, Yahoo!, Framework, JSON

Layout Manager in action - build your own Yahoo Mail

Version 2.5 of the Yahoo User Interface Library (YUI) was released today. You can get all the details on the official blog post, but here's the "change log":

  • The new Layout Manager allows you to create multi-pane user interfaces that are collapsible and resizable.
  • The Flash-enhanced File Uploader control might be known to you from Flickr and and allows you to easily batch-upload files and images with progress bars.
  • The JavaScript Profiler now has a graphical front-end to make the information more easily understandable
  • The YUI Data Table performs faster and got new features, including horizontal and vertical scrolling, a paginator class, drag and drop columns and an API to access, add and remove columns.
  • The Image Cropper control allows you to pick a part of an image to be cropped server-side
  • The Cookie Controller provides a wrapper for all things to do with cookies
  • The Slider Control got updated to support multiple handles to define a range rather than just a state.

In addition to that, some of the components left beta status. These are the Get Utility to retrieve scripts and style sheets on the fly, the ColorPicker Control, the JSON Utility to validate JSON, the ImageLoader Utility to load images on-demand to increase page performance and the YUI Test Utility.

The really detailed report on all the changes is available on the YUI list/forum.

If you want to have a quick glimpse of what the Layout Control allows you to create, check out the demo application interface simulating simulating Yahoo Mail.

Posted by Chris Heilmann at 5:30 pm
7 Comments

++++-
4.2 rating from 42 votes

Tuesday, February 12th, 2008

LINQ to JSON

Category: .NET, JSON

James Newton-King has posted a new bit of code called LINQ to JSON which is a .NET LINQ style API over JSON.

For example, here is how you could get out categories and how often they are used:

JAVASCRIPT:
  1.  
  2. var categories =
  3.   from c in rss.PropertyValue<jobject>("channel")
  4.               .PropertyValue<jarray>("item")
  5.               .Children<jobject>()
  6.               .PropertyValues<jarray>("category")
  7.               .Children<string>()
  8.   group c by c into g
  9.   orderby g.Count() descending
  10.   select new { Category = g.Key, Count = g.Count() };
  11.  

There is also a project, JSLINQ which is an implementation of LINQ to Objects implemented in JavaScript. It is built using a set of extension methods built on top of the JavaScript Array object. If you are using an Array, you can use JSLINQ.

Posted by Dion Almaer at 7:00 am
5 Comments

+++--
3.8 rating from 20 votes

Friday, February 1st, 2008

Google Social Graph API Released

Category: Google, JSON, Social Networks

Reposted from my blog

Would you like to be able to make a quick call to get a JSON response that ties together a social graph made up of resources available on the Web?

Social Graph API

Brad Fitzpatrick, Kevin Marks, and others at Google have released a new Social Graph API that does just that:

The new Social Graph API makes information about the public connections between people on the Web easily available and useful. You can make it easy for users to bring their existing social connections into a new website and as a result, users will spend less time rebuilding their social networks and more time giving your app the love it deserves.

Here's how it works: we crawl the Web to find publicly declared relationships between people's accounts, just like Google crawls the Web for links between pages. But instead of returning links to HTML documents, the API returns JSON data structures representing the social relationships we discovered from all the XFN and FOAF. When a user signs up for your app, you can use the API to remind them who they've said they're friends with on other sites and ask them if they want to be friends on your new site.

This is exciting to me as:

I gave it a quick test drive, and when I say quick, I mean 5 minutes :)

I built a tiny JavaScript library that takes a base URL, and it graphs out the relationships using Canvas.

You get to call loadGraph(URL, { width: w, height: h }) and the graph will be injected away.

It needs to be nicely abstracted and isolated so you can call it willy-nilly, but it works.

Watch the introduction video:


Posted by Dion Almaer at 2:13 pm
2 Comments

+++--
3.6 rating from 21 votes

Thursday, January 31st, 2008

JSON 2.0: Libraries and browser support

Category: JavaScript, Library, Browsers, JSON

John is at it again, writing a piece on recent news surrounding JSON.

He links to an updated library by Douglas Crockford,

JAVASCRIPT:
  1.  
  2. JSON.stringify({name: "John", location: "Boston"});
  3. // => "{'name':'John','location':'Boston'}"
  4. JSON.parse("{'name':'John','location':'Boston'}");
  5. // => {name: "John", location: "Boston"}
  6.  

It also turns out that Mozilla implemented this functionality in the browser (time for a wrapper):

JAVASCRIPT:
  1.  
  2. var nativeJSON = Components.classes["@mozilla.org/dom/json;1"]
  3.     .createInstance(Components.interfaces.nsIJSON);
  4. nativeJSON.encode({name: "John", location: "Boston"});
  5. // => "{'name':'John','location':'Boston'}"
  6. nativeJSON.decode("{'name':'John','location':'Boston'}");
  7. // => {name: "John", location: "Boston"}
  8.  

And in conclusion:

The final, and most important, step is being worked on right now - a way to access native JSON encoding and decoding from web pages. How it'll be accessible is up to some debate (as having its naming conflict with an existing object would be a really bad thing). Regardless, there should be something within the browser by the time the Firefox 3 betas wrap-up.

Posted by Dion Almaer at 5:00 am
2 Comments

++++-
4.7 rating from 15 votes

Friday, January 18th, 2008

JSONLib: JSON Extensions a la E4X

Category: JavaScript, Library, JSON

Nicholas C. Zakas wanted to keep JSON out of JavaScript. He has patterned a new form of JSON support on E4X and wrote it up.

Nichole wants:

  • The addition of two new global types: JSON and JSONList. JSON represents a JSON object while JSONList represents a JSON array.
  • Both types have a toJSONString() method that correctly encodes an object into a JSON string. The default toString() method is available but returns a string representation of the object (not a JSON string). This follows the convention set forth in E4X.
  • The [[Put]] method is overridden in both types such that it will only accept values of type JSON, JSONList, Date, boolean, string, number, or null. Any other data types cause an error to be thrown.
  • The JSON constructor allows an object to be passed in that has initial properties to add; the JSONList constructor allows an array to be passed in with items to add.
  • The typeof operator should return "json" when used on a value of type JSON or JSONList.
  • JSON strings are parsed via JSON.parse(), throwing syntax errors if they are found.

You can see it in action:

JAVASCRIPT:
  1.  
  2. var obj = JSON.parse("{\"name\":\"Nicholas\",\"age\":29}");
  3.  
  4. var json = new JSON();
  5. json.put("name", "Nicholas");
  6. json.put("age", 29);
  7. var name = json.get("name");
  8. var str = json.toJSONString();
  9.  
  10. var list = new JSONList();
  11. list.put(0, "blah");
  12. list.push(25);
  13. list.push(true);
  14. var val = list.get(1