Activate your free membership today | Log-in

Monday, January 11th, 2010

Using YQL as a proxy for cross-domain Ajax

Category: JSON, JavaScript, XmlHttpRequest, Yahoo!, jQuery

OK, this is nothing shockingly new, but I found it pretty useful. Using jQuery, Ajax has become more or less a one-liner:

JAVASCRIPT:
  1. $(document).ready(function(){
  2.   $('.ajaxtrigger').click(function(){
  3.     $('#target').load($(this).attr('href'));
  4.     return false;
  5.   });
  6. });

This loads the document any link with a class of "ajaxtrigger" points to and updates the content of the element with the ID "target". If the link is a third party link on another domain it fails though - and silently at that. Normally you'd work around that with a server-side proxy, but you can actually do without it.

YQL is a hosted web service that can scrape HTML for you. It also runs the HTML through HTML Tidy and caches it for you. For example to load http://bbc.co.uk you'd use the following statement:

CODE:
  1. select * from html where url='http://bbc.co.uk'

As a URL this turns into:

CODE:
  1. http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D'http%3A%2F%2Fbbc.co.uk'%0A&format=xml
  2.  

You could request JSON-P by setting the output format to json and define a callback, but that would give the HTML back as a massive object which is not nice. YQL also offers JSON-P-X as an alternative which is a JSON object with a callback and the HTML as a string inside a simple Array. See it by clicking the following URL:

http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%27http%3A%2F%2Fbbc.co.uk%27%0A&format=xml&diagnostics=false&callback=foo

Now, using jQuery's getJSON() we can load this even without a named callback function. That way we can use one method for content that is third party and simply use load() for the other:

JAVASCRIPT:
  1. $(document).ready(function(){
  2.   var container = $('#target');
  3.   $('.ajaxtrigger').click(function(){
  4.     doAjax($(this).attr('href'));
  5.     return false;
  6.   });
  7.   function doAjax(url){
  8.     if(url.match('^http')){
  9.       $.getJSON("http://query.yahooapis.com/v1/public/yql?"+
  10.                 "q=select%20*%20from%20html%20where%20url%3D%22"+
  11.                 encodeURIComponent(url)+
  12.                 "%22&format=xml'&callback=?",
  13.         function(data){
  14.           if(data.results[0]){
  15.             container.html(data.results[0]);
  16.           } else {
  17.             var errormsg = '<p>Error: could not load the page.</p>';
  18.             container.html(errormsg);
  19.           }
  20.         }
  21.       );
  22.     } else {
  23.       $('#target').load(url);
  24.     }
  25.   }
  26. });

You can see the demo in action here, more details are available on my blog and the source is available on GitHub.

Posted by Chris Heilmann at 7:42 pm
8 Comments

+++--
3.4 rating from 27 votes

Wednesday, December 23rd, 2009

Orderly JSON

Category: JSON, JavaScript, Library

Lloyd Hilaiel of Yahoo! BrowserPlus fame, has a little holiday gift for us. He has created a simple library called Orderly that "is a textual format for describing JSON. Orderly can be compiled into JSONSchema. It is designed to be easy to read and write."

He shares:

A little bit of orderly...

JAVASCRIPT:
  1.  
  2. object {
  3.   string name;
  4.   string description?;
  5.   string homepage /^http:/;
  6.   integer {1500,3000} invented;
  7. }*;
  8.  

...describes a little bit of JSON...

JAVASCRIPT:
  1.  
  2. {
  3.   "name": "orderly",
  4.   "description": "A schema language for JSON",
  5.   "homepage": "http://orderly-json.org",
  6.   "invented": 2009
  7. } 
  8.  

...and compiles into JSONSchema.

JAVASCRIPT:
  1.  
  2. {
  3.   "type": "object",
  4.   "properties": {
  5.     "name": {
  6.       "type": "string"
  7.     },
  8.     "description": {
  9.       "type": "string",
  10.       "optional": true
  11.     },
  12.     "homepage": {
  13.       "type": "string",
  14.       "pattern": "^http:"
  15.     },
  16.     "invented": {
  17.       "type": "integer",
  18.       "minimum": 1500,
  19.       "maximum": 3000
  20.     }
  21.   },
  22.   "additionalProperties": true
  23. }
  24.  

Go into detail on Orderly in the documentation or try the
interactive by-directional Orderly - JSONSchema area.

Posted by Dion Almaer at 6:34 am
13 Comments

+++--
3 rating from 29 votes

Wednesday, September 9th, 2009

Getting hyper about JSON namespacing

Category: JSON

Kris Zyp, JSON hero, has been cooking up some more good stuff on his path to reinventing a new path to all.

In JSON namespacing he discusses JSON Hyper Schema which aims to cure JSON from XML namespacing colon cancer.

JSON Hyper Schemas can be referenced from instances by Link headers or media type parameters. A simple example illustrates how JSON properties have universally locatable definitions:

JAVASCRIPT:
  1.  
  2. Content-Type: application/json; schema=http://www.book-warehouse.com/book-schema
  3. [
  4.   {"title": "Oliver Twist", "price": 16.99},
  5.   {"title": "Robinson Crusoe", "price": 15.99}
  6. ]
  7.  

This message gives the authoritative URI for the schema. With a look at the schema, we can see how each property has a corresponding definition with an authoritative URI as well:

JAVASCRIPT:
  1.  
  2. Content-Type: application/schema+json; schema=http://json-schema.org/hyper-schema
  3. {
  4.   "properties": {
  5.      "title": {"type": "string", "description": "The title of the book"},
  6.      "price": {"type": "number", "description": "The price of the book in US"},
  7.   }
  8. }
  9.  

JSON Hyper Schema is a sufficient building block upon which we can realize the goals of namespacing, namely, meanings from distributed parties can be authoritatively ascribed to elements of a data structure with property name sharing and conflict resolution control. What is elegant about this approach is that basically nothing needs to be modified in the actual instance data structures themselves. URI attribution is done through media type parameters in combination with schemas. The actual data stays unchanged, it is still the original simple, easy to read, compact JSON. JSON namespacing not only fits with JSON technically, but it fits in spirit: data is simple and light.

Posted by Dion Almaer at 6:42 am
9 Comments

++++-
4.1 rating from 20 votes

Tuesday, July 28th, 2009

Dynamic script generation and memory leaks

Category: JSON, Performance

An interesting piece by Neil Fraser shows that using JSON-P with generated script nodes can be quite a memory leak. Normally you'd add information returned from an API in JSON-P with a generated script node:

JAVASCRIPT:
  1. script = document.createElement('script');
  2.   script.src = 'http://example.com/cgi-bin/jsonp?q=What+is+the+meaning+of+life%3F';
  3.   script.id = 'JSONP';
  4.   script.type = 'text/javascript';
  5.   script.charset = 'utf-8';
  6.   // Add the script to the head, upon which it will load and execute.
  7.   var head = document.getElementsByTagName('head')[0];
  8.   head.appendChild(script)

The issue there is that you clog up the head of the document with lots of script nodes, which is why most libraries (like the YUI get() utility) will add an ID to the script element and remove the node after successfully retrieving the JSON data:

JAVASCRIPT:
  1. var script = document.getElementById('JSONP');
  2. script.parentNode.removeChild(script);

The issue with this is that browsers do remove the node but fail to do a clean garbage collection of the JavaScript at the same time. This means to cleanly remove the script and its content, you need to also delete the properties of the script by hand:

JAVASCRIPT:
  1. // Remove any old script tags.
  2.   var script;
  3.   while (script = document.getElementById('JSONP')) {
  4.     script.parentNode.removeChild(script);
  5.     // Browsers won't garbage collect this object.
  6.     // So castrate it to avoid a major memory leak.
  7.     for (var prop in script) {
  8.       delete script[prop];
  9.     }
  10.   }

Read the whole post here

Posted by Chris Heilmann at 3:50 pm
17 Comments

++++-
4 rating from 25 votes

Thursday, July 9th, 2009

Pimping JSON – YQL now offers JSONP-X!

Category: JSON, JavaScript, Yahoo!

Yesterday's announcement of Yahoo's YQL now supporting insert, update and delete overshadowed another interesting new feature: JSONP-X output.

Here's what it is and why it is useful: YQL data can be returned in XML which is annoying to use in JavaScript (for starters because of crossdomain issues in Ajax). JSON is much easier as it is native to JavaScript. JSON-P makes it even more easy for us to use as JSON data wrapped in a function call allows us to get the data by creating script nodes dynamically.

Where it falls apart is when you want to get back HTML from some system (not on your own server) and use it in JavaScript. You either need to convert the XML to JavaScript and create HTML elements from it or you need to loop through a JSON construct and assemble HTML from it. JSONP-X works around that step for you. In essence it is XML as a string returned inside a JSON object.

XML:

XML:
  1. <results>
  2.   <div id="following">
  3.     <span>
  4.       <a href="http://twitter.com/codepo8">Codepo8</a>
  5.     </span>
  6.   </div>
  7. </results>

JSON:

JAVASCRIPT:
  1. {"results":[
  2.   "div":{
  3.     "id":"following",
  4.    "span":{
  5.      "a":{
  6.        "href":"http://twitter.com/codepo8",
  7.        "text":"Codepo8"
  8.      }
  9.    }
  10.  }
  11. ]}

JSON-P:

JAVASCRIPT:
  1. foo({"results":[
  2.   "div":{
  3.     "id":"following",
  4.    "span":{
  5.      "a":{
  6.        "href":"http://twitter.com/codepo8",
  7.        "text":"Codepo8"
  8.      }
  9.    }
  10.  }
  11. ]})

JSONP-X:

JAVASCRIPT:
  1. foo({"results":[
  2. "<div id=\"following\"><span><a href=\"http://twitter.com/codepo8\">Codepo8</a></span></div>"
  3. ]})

The way to invoke the JSONP-X output is to provide a format parameter of xml and a callback parameter.

This allows me for example to get the list of people I follow on twitter from my twitter homepage and display it in another document with a few lines of JavaScript without any need of using the API or having a local proxy:

HTML:
  1. <script type="text/javascript" charset="utf-8">
  2. function foo(o){
  3.   var out = document.getElementById('container');
  4.   var content = o.results[0]
  5.   out.innerHTML = content.replace(/href="\//g,'href="http://twitter.com/');
  6. }
  7. </script>   
  8. <script type="text/javascript" src="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Ftwitter.com%2Fcodepo8%22%20and%20xpath%20%3D%20%22%2F%2Fdiv[%40id%3D%27following_list%27]%22&format=xml&callback=foo">
  9. </script>

More details on this are available in this blog post.

Posted by Chris Heilmann at 10:48 am
7 Comments

++---
2.3 rating from 39 votes

Thursday, July 2nd, 2009

GeoMaker – geo locations as microformats or a map from texts or URLs

Category: JSON, JavaScript, Yahoo!

As preparation for an upcoming tech talk about Placemaker I thought it would be good to take a bit of the pain out of the geolocation service by making an interface for it. Placemaker works the following way: you post some content or a URL to it, it goes through the content or gets the content from the URL and analyzes it. It then finds geographical locations in the text and disambiguates them (for example to skip names like "Jack London" and not consider it the city London). Finally you get it back as XML.

The annoying thing is that Placemaker only support POST request and does not have a JSON output - for now. GeoMaker allows non-developers to enter some text or a URL, filter the results (using YUI datatable) to remove false positives (no system is perfect) and get the embed code for a Yahoo Map or a list of microformatted locations as copy+paste. See the screencast to get the end user experience:

Of course, every time you build something like that, red-blooded developers will ask for an API to do the same thing (and pointing them to Placemaker wasn't enough). So here it is:

http://icant.co.uk/geomaker/api.php takes two parameters: url of the web document to load and output which could be map, kml, microformats, csv, or json (with callback for JSON-P). Using this you can analyze a url in JavaScript and get the data back as an array:

HTML:
  1. <script>function geomaker(o){
  2.   for(var i=0,j=o.length;i<j ;i++){
  3.     // o[i] will have lat, lon, title and match
  4.   }
  5. }</script>
  6. <script src="http://icant.co.uk/geomaker/api.php?url=http://ajaxian.com&output=json&callback=geomaker"></script>

The Ajaxian.com output right now would be:

JAVASCRIPT:
  1. geomaker(
  2.   [
  3.     {"lat":"42.3586","lon":"-71.0567",
  4.      "title":"Boston, MA, US","match":"Boston"},
  5.     {"lat":"42.3586","lon":"-71.0567",
  6.      "title":"Boston, MA, US","match":"Boston, MA"},
  7.     {"lat":"40.7075","lon":"-106.918","title":"Clark, CO, US",
  8.      "match":"Clark, Co"},
  9.     {"lat":"42.3115","lon":"43.3658","title":"Georgia",
  10.      "match":"Geo"},
  11.     {"lat":"44.9601","lon":"7.16229",
  12.      "title":"Rey, Piedmont, IT","match":"Rey"}
  13.   ])
  14.  

Posted by Chris Heilmann at 3:02 am
8 Comments

+++--
3.7 rating from 12 votes

Thursday, June 18th, 2009

JavaScript Compatibility Tests

Category: JSON, JavaScript

Robert Nyman has setup a really nice test suite for JavaScript 1.6, 1.7, and 1.8+ features such as getters/setters, Object.defineProperty, Object.getPrototypeOf, new String extras, and JSON.

It includes compatibility tables, and will try to run the tests on your browser to give you feedback. It also includes sample code to check web browser support that you can use in your own projects.

Nice job Robert!

Posted by Dion Almaer at 10:25 am
2 Comments

++++-
4.6 rating from 20 votes

Monday, June 15th, 2009

Bing API does callback checking for JSON-P

Category: JSON, JavaScript, Library

I just looked through the API of Microsoft's new Bing search and found an interesting step in protecting code from throwing errors.

When you provide a JSON output for developers it does make sense to also allow for a callback parameter. That way your code can be used in script nodes without having to use any backend at all. Commonly this is called JSON-P and has been covered here in the long long ago. One of the issues with JSON-P is that when the callback method is not defined it throws an error.

The Bing API is the first instance where I have seen that they worked around that as the output is this:

JAVASCRIPT:
  1. if(typeof callback == 'function') callback(
  2. {
  3.   "SearchResponse":
  4.   {
  5.     "Version":"2.2",
  6.     "Query":
  7.       {
  8.         "SearchTerms":"a hard day's night"
  9.       },
  10.     "Translation":
  11.       {
  12.         "Results":
  13.           [
  14.             {"TranslatedTerm":"einem harten Tag-Nacht "}
  15.           ]
  16.       }
  17.     }
  18. } /* pageview_candidate */);

I have no clue what the /* pageview_candidate */ is about and frown upon omitting the {} of the if statement, but I must say I do like this. One issue is that while end users don't get annoyed with errors, developers don't have a clue what happened either as the error is silent. One proposal would be to use a console.log() when there is an error:

JAVASCRIPT:
  1. if(typeof callback === 'function') {
  2.   callback(... data ... );
  3. } else {
  4.   if (typeof console!=='undefined' &&
  5.    typeof console.log !== 'undefined'){
  6.     console.log('Error: Callback method not defined');
  7.   }
  8. }

More details about other ideas to improve this are here.

Posted by Chris Heilmann at 6:32 am
19 Comments

++---
2.3 rating from 31 votes

Tuesday, April 21st, 2009

Persevere’s JavaScriptDB: Impressive JSON Performance

Category: Database, JSON, JavaScript

Kris Zyp recently posted about an intriguing new chapter in the application persistence space:

The latest beta of Persevere features a new native object storage engine called JavaScriptDB that provides high-end scalability and performance. Persevere now outperforms the common PHP and MySQL combination for accessing data via HTTP by about 40% and outperforms CouchDB by 249%. The new storage engine is designed and optimized specifically for persisting JavaScript and JSON data with dynamic object structures. It is also built for extreme scalability, with support for up to 9,000 petabytes of JSON/JS data in addition to any binary data.

This comparison isn't exactly apples-to-apples as it turns out–for the web app use case, Perservere has a bunch of value-adds on top of data storage:

Persevere/JavaScriptDB goes further [than relational DBs] with the flexibility to evolve schemas and handle partial schemas. Persevere also provides integrated server side JavaScript (SSJS) with persistence, Comet-driven data change notifications, JSONQuery, standards based HTTP interface with content negotiation, JSON-RPC interface to SSJS, cross-domain handling, CSRF protection, and more. All of these things are additional features that one would have to add to the stack for other storage systems, making them even slower. Persevere includes this functionality out of the box, while still maintaining extremely fast performance.

Kris spends a bit of time in his post explaining his test setup, but then gets to the good stuff:

So how does Persevere achieve this level of performance with the JavaScriptDB storage? The dynamic object-oriented nature of the data that is stored in JavaScriptDB is much different than that of a traditional relational database, so a number of innovative approaches were employed.

He goes into quite a bit of detail explaining the implementation details behind JavaScriptDB. The summary (with lightly edited quotes) is:

  • Direct Data-Bound Object Representation: "In a traditional application stack, a record must have separate in-memory representations for [the database] and [the application] result set which then might be mapped to an object representation. With JavaScriptDB, the single in-memory object is reused for all result sets and data caching."
  • Shared Cache of Objects with Copy-on-Write
  • Append-based Database Storage: "Many traditional database commit data to a transaction log before committing data to the table, requiring multiple writes. JavaScriptDB appends transactional data directly to the main storage file; writes can be committed with a single IO operation."
  • Adaptive On-Demand Concurrent Indexing
  • Batched writes in integrity mode
  • Pluggable Storage

Check out the full post all the details.

Posted by Ben Galbraith at 1:00 pm
4 Comments

++++-
4.7 rating from 47 votes

Browsing on the Couch

Category: Database, JSON, JavaScript, Library

Atul Varma, a fantastic colleague in Building "S" at Mozilla, has been playing with a JavaScript implementation of CouchDB called BrowserCouch:

BrowserCouch is an attempt at an in-browser MapReduce implementation. It's written entirely in JavaScript and intended to work on all browsers, gracefully upgrading when support for better efficiency or feature set is detected.

Not coincidentally, this library is intended to mimic the functionality of CouchDB on the client-side, and may even support integration with CouchDB in the future.

Why?

This prototype is intended as a response to Vladimir Vuki?evi?'s blog post entitled HTML5 Web Storage and SQL. A CouchDB-like API seems like a nice solution to persistent storage on the Web because so many of its semantics are delegated out to the JavaScript language, which makes it potentially easy to standardize. Furthermore, the MapReduce paradigm also naturally takes advantage of multiple processor cores—something that is increasingly common in today's computing devices.

There is also an interactive CouchDB project that "is an emulator written in 100% JavaScript with tons of jQuery thrown in. It also implements the collation schemes as well as the map/reduce algorithms. While it doesn’t demonstrate replication, conflict management and a host of other capabilities in CouchDB, it does strive to illustrate concepts like schema-less JSON documents, map/reduce and how these things fit together."

You can check out the emulator here.

Posted by Dion Almaer at 6:34 am
1 Comment

+++--
3.7 rating from 18 votes

Monday, April 20th, 2009

How JSON Schema is turning out for the Chrome extension APIs

Category: Chrome, JSON

When Aaron talked about the Chrome extension API he mentioned how he would see if JSON Schema could help them have a JSON heavy API and allow them to easily validate.

He has quickly reported back and is happy with the results.

Something like this:

JAVASCRIPT:
  1.  
  2. chromium.tabs.createTab = function(tab, callback) {
  3.   validate(arguments, arguments.callee.params);
  4.   sendRequest(CreateTab, tab, callback);
  5. };
  6.  
  7. chromium.tabs.createTab.params = [
  8.   {
  9.     type: "object",
  10.     properties: {
  11.       windowId: chromium.types.optPInt,
  12.       url: chromium.types.optStr,
  13.       selected: chromium.types.optBool
  14.     },
  15.     additionalProperties: false
  16.   },
  17.   chromium.types.optFun
  18. ];
  19.  

will give you errors such as:

Invalid value for parameter 0. Property windowId: expected integer, got string.

It will be interesting to see how the APIs look when you go for this style throughout. Looking forward to see more.

Posted by Dion Almaer at 5:19 am
3 Comments

++++-
4.2 rating from 10 votes

Wednesday, March 18th, 2009

Super fast client side searches – the Flickr way

Category: Examples, JSON, Performance, XmlHttpRequest, Yahoo!

Over at the Flickr development blog, Ross Harmes, one of those lesser sung JavaScript heroes explains in detail how Flickr creates really fast client side searches and one of the implementations of these findings is the newly released find people faster feature:

find people faster feature on flickr

The main findings of the team were that eval() is not only evil but also very slow whereas dynamic script nodes are fast but insecure. The solution was to do a custom evaluation of string data rather than using JSON:

Having set the performance bar pretty high with the last approach, we dove into custom data formats. The challenge would be to create a format that we could parse ourselves, using JavaScript’s String and RegExp methods, that would also match the speed of JSON executed natively. This would allow us to use Ajax again, but keep the data restricted to our domain.

Since we had already discovered that some methods of string manipulation didn’t perform well on large strings, we restricted ourselves to a method that we knew to be fast: split(). We used control characters to delimit each contact, and a different control character to delimit the fields within each contact. This allowed us to parse the string into contact objects with one split, then loop through that array and split again on each string.

JAVASCRIPT:
  1. that.contacts = o.responseText.split("\\c");
  2.  
  3. for (var n = 0, len = that.contacts.length, contactSplit; n &lt;len; n++) {
  4.  
  5.         contactSplit = that.contacts[n].split("\\a");
  6.  
  7.         that.contacts[n] = {};
  8.         that.contacts[n].n = contactSplit[0];
  9.         that.contacts[n].e = contactSplit[1];
  10.         that.contacts[n].u = contactSplit[2];
  11.         that.contacts[n].r = contactSplit[3];
  12.         that.contacts[n].s = contactSplit[4];
  13.         that.contacts[n].f = contactSplit[5];
  14.         that.contacts[n].a = contactSplit[6];
  15.         that.contacts[n].d = contactSplit[7];
  16.         that.contacts[n].y = contactSplit[8];
  17. }

Once this had been speeded up, all they needed to use was the YUI AutoComplete control and voilà - fast client side searches even with massive datasets.

Posted by Chris Heilmann at 2:38 pm
8 Comments

+++--
3.7 rating from 17 votes

Thursday, February 26th, 2009

JSONView: JSON browser from within Firefox

Category: JSON, Utility

JSONView is a new Firefox extension that gives you a nice way to view your JSON documents (JSONovich also does the trick).

Ben Hollis talks about the extension:

The extension itself is pretty simple. I wasn’t sure how to approach the problem of supporting a new content type for Firefox, so I followed the example of the wmlbrowser extension and implemented a custom nsIStreamConverter. What this means is that I created a new component that tells Firefox “I know how to translate documents of type application/json into HTML”. And that it does - parsing the JSON using the new native JSON support in Firefox 3 (for speed and security) and then constructing an HTML document that it passes along the chain. This seems to work pretty well, though there are some problems - some parts of Firefox forget the original type of the document and treat it as HTML, so “View Page Info” reports “text/html” instead of “application/json”, “Save as…” saves the generated HTML, Firebug sees the generated HTML, etc. Just recently I came across the nsIURLContentListener interface, which might offer a better way of implementing JSONView, but I’m honestly not sure - the Mozilla documentation is pretty sparse and it was hard enough to get as far as I did. I’m hoping some Mozilla gurus can give me some pointers now that it’s out in the open.

Posted by Dion Almaer at 10:31 am
4 Comments

++++-
4.5 rating from 12 votes

Monday, February 16th, 2009

Native JSON in Firefox 3.1; Joins IE 8

Category: Browsers, JSON

The native JSON API is part of the upcoming 3.1 revision of ECMAScript, so we should see it adopted in browsers pretty quickly. It’s also API compatible with json2.js, as you note, so many many web users will get the performance win without apps needing to update.

I suspect that the performance advantage for native JSON is even more pronounced on the encoding side, but I don’t have tests to hand to back it up.

This was a comment by Mike Shaver, VP of Engineering at Mozilla (disclaimer: where I work).

The comment related to the post on the native JSON support in Firefox 3.1:

In case you haven’t heard, one of Firefox 3.1’s awesome new features will be native JSON support. This is totally sweet for two reasons:

  1. eval’ing JSON in the browser is unsafe. Using native JSON parsing protects you against possible code execution.
  2. Safely eval’ing JSON with a 3rd party library can be orders of magnitude slower. Native JSON parsing is much faster.

How does native JSON work compared to plain old eval? Simple:

var jsonString = '{"name":"Ryan", "address":"Mountain View, CA"}';
var person = JSON.parse(jsonString);
// 'person' is now a JavaScript object with 2 properties; name and address

Pretty easy huh? And here’s how to get a JSON string from an object:

var personString = JSON.stringify(person);
// 'personString' now holds the string '{"name":"Ryan", "address":"Mountain View, CA"}'

“But wait!”, you say. “How is it safer? How much faster is it compared to eval?”. Ok, I’ll show you.

Gotta love it when browsers implement something that just starts to make apps faster without potentially knowing about it.

Posted by Dion Almaer at 4:05 am
8 Comments

++++-
4.5 rating from 28 votes

Wednesday, February 11th, 2009

JsonML: Who needs angle brackets?

Category: JSON

JsonML swaps out the world of the curly with that of the angle.

The purpose of JsonML is to provide a compact format for transporting XML-based data via JSON.

Simon Willison says it best:

An almost non-lossy serialization format for sending XML as JSON (plain text in between elements is ignored). Uses the (element-name, attribute-dictionary, list-of-children) tuple format, which sadly means many common cases end up taking more bytes than the original XML. Still an improvement on serializations that behave differently when a list of children has only one item in it.

Have you seen this path before? Hating on XML and going for JSON, but then trying to JSON as XML and at the end of it you just s/</{/g.

Just take a look at the GData JSON API

Posted by Dion Almaer at 6:39 am
22 Comments

++---
2.7 rating from 32 votes

Wednesday, February 4th, 2009

Kiva: Making a difference with a new API

Category: JSON, Library

We don't often post about general APIs. I let John Musser handle that on Programmable Web, but this one strikes a chord with me.

Kiva, the distributed micro loan platform, has released a new developer API that gives third parties access to create innovative applications on top of the platform:

The initial release of the Kiva API is concerned with helping you find and present public data from Kiva. We want to help you find things like loans, lenders, and partners and help you represent those in your applications and products. We think there are a lot of really useful things that can be done just by helping the Kiva community find information in different ways or experience it in a new context. Moreover, understanding our core set of data is the most important building block to doing more complex operations in future versions of the API.

One chap has already started to map out lenders and loans:

I have just started poking at the data available, as I suspect network analysis will be able to help predict rates of return.

When I knew that Skylar Woodward was in on the action I knew something cool was coming. The API so far is typically JSON and RESTful (and XML if you haaave too). I wonder if anyone has written a nice JavaScript wrapper around the API yet?

Posted by Dion Almaer at 12:05 am
5 Comments

+++--
3.8 rating from 12 votes

Next Page »