Using JSON to Exchange Data

Javascript Object Notation (JSON) is a fancy name for a simple idea: A web page can download data stored as javascript variables. It’s caused a buzz in the tech world because JSON is much easier to load, read and manipulate compared to XML. Also, parsing large XML files can be a large performance hit – JSON gives you an object, packaged up and ready to go!

Remember the script tag?

In javascript you can import any script using notation like this:

<script src="http://www.mysite.com/myscript.js"></script>

The browser will pull down the script and run it inside the current page. This is how embeddable widgets like Adsense and InstaCalc work.

The neat thing is that any variables and functions defined inside the script are available to the page. If myscript.js includes a function showMeTheMoney(), your page can call it (and, presumably, get shown the money).

This is all fine and dandy, and been known for a while. A cool use is to provide dynamic data to a page with encoded Javascript variables. If the variables were “objects” and we passed them using their special “notation”, we could call the system JavaScript Object Notation. (Technically, JSON just covers the “object” part; executable functions are dynamic javascript).

In Javascript, you can use objects like this:

var fruit = {}; // create new obj
fruit.name = "apple"; // set properties
fruit.color = "red";

// that is old fashioned! Try my new notation:

var fancyFruit = {"name":"pear", "color": "greenish"};

Javascript has a nice notation where you can define objects using "key":"value" pairs. You can define arrays and functions this way too, so your objects are more like a class, in fact.

So why is this useful again?

So far, passing scripts around is old news. But an idea comes along: what if you load a dynamically generated script, which has data inside of it? Now you can access the data as javascript variables. Here’s what I mean:

<script src="http://www.weathersite.com/latestweather.js"></script>
Today's weather is:
<script>
document.write(Weather.today);
</script>

See what’s happening here? We load the javascript (which could be updated every hour by the server), and access the Weather object it defines. Presumably, Weather.today is a string containing today’s weather. Realistically, we could have Weather[zipcode] or whatever format the site defines.

Cool, huh?

But why not XML?

Ah — some programmers will say “Verily, can you not download an XML file, and then process and parse it into Javascript variables?”

Sure, just like you can run a marathon or floss your teeth. Many want to, some try to, not everybody does.

XML is fine for certain things, but it can be quite cumbersome. JSON is great because you can include data in an easy, painless process. There’s no parsing step – you are getting your variables “for free” by just including the javascript file.

Also, JSON lets the site include functions, which may be used to process the data or handle other tasks.

A few details (as always)

There are various ways to use JSON (see links for source of code sample):

  • Include a script tag directly (as above). This means the code inside the script is run immediately as the browser encounters it.
<script src="http://www.mysite.com/mydata.js"></script>
function dhtmlLoadScript(url)
{
   var e = document.createElement("script");
   e.src = url;
   e.type="text/javascript";
   document.getElementsByTagName("head")[0].appendChild(e); 
}
dhtmlLoadScript("http://www.mysite.com/mydata.js");
  • Use AJAX (Xml Http Request) to pull some text from the server and then eval it. Note that the first two techniques automatically “eval” the javascript because it is inside a script tag. You probably want to use a library to do the XHR request (like AjaxCaller):
ajaxCaller.getPlainText("mydata.js", 
   function(jsText) { eval(jsText); });

Note that XHR requests can only open files on the same domain as the caller. The first two techniques can load a file from any domain.

Security, Security, Security

I’m not an expert in Web Security, but I know enough to realize it’s tricky and that there will be things I miss. Even the big boys like Google can get caught in bugs sometimes.

The safest approach is to only store public data with JSON. If you store private data in JSON (or XML for that matter), there are techniques where malicious sites can impersonate logged-on users. Yes, there are complicated workarounds for the security problems (like double-submitting cookies). But if you’re starting out (like me), start off using JSON for public info you don’t mind having disclosed (like weather reports).

Callbacks

The JSON data may not be a raw object; it could be an object passed to a callback function, such as:

specialFunction( {"name" : "Bob", "email": "bob@example.com"} );

In this case, the script will run a function called specialFunction that you’ve defined, passing it an anonymous object with a “name” and “email” property. Your specialFunction can then do wild things with this information.

This technique is the same at heart – this is how Google originally passed your Gmail contacts. Sometimes you can specify the name of your callback function in the URL you use to access the JSON data – it depends on the data provider.

Real-life example: Currency conversion in InstaCalc

I recently added currency conversion to the InstaCalc Online Calculator, which was a good lesson in importing data:

  • Find your data source. The Federal Bank of New York has an XML file with currency conversion data. That’s good enough for me!
  • Convert data to JSON format. You can convert XML to JSON using XSLT transformations.
  • Install XALAN so you can do XSL transformations using Java. A typical transformation looks like this:
java org.apache.xalan.xslt.Process -classpath "xalan.jar" 
-IN in.xml -XSL in.xslt > out.xml

Be careful for Java classpath issues, I had trouble and had to include the classpath to xalan.jar manually.

  • Convert XML attributes to elements. Attributes can be difficult to access in the various XML to JSON scripts, so make them elements. Use this XSL to convert attributes to elements:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   version="1.0">
  <xsl:output indent="yes" />
  <xsl:strip-space elements="*" />
  <xsl:template match="*">
    <xsl:copy>
      <xsl:if test="@*">
        <xsl:for-each select="@*">
          <xsl:element name="{name()}">
            <xsl:value-of select="." />
          </xsl:element>
        </xsl:for-each>
      </xsl:if>
      <xsl:apply-templates />
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>

Then process the XML file using XALAN:

java org.apache.xalan.xslt.Process -classpath "xalan.jar" 
-IN in.xml -XSL attributes-to-elements.xslt > no-attributes.xml
  • Finally, convert the XML to JSON using this XSL transformation. There are several XML 2 JSON stylesheets out there if you search.

Run your XML through XALAN to create the final JSON data.

java org.apache.xalan.xslt.Process -classpath "xalan.jar" 
-IN no-attributes.xml -XSL xml2json.xslt > currencies.json
  • Clean up your data. You have the raw JSON data as an object, but you may wish to wrap it in a function call. You can use a quick perl script to wrap “myFunction( )” around the data above so your file does a callback when executed.

Tada! Now you have JSON data ready to access using one of the techniques above (see the currency JSON data). Inside InstaCalc, I have a static reference to the file:


<script src="http://instacalc.com/data/currencies.json"><script>

Because the bank has some namespace information, I access variables like this inside the callback function: data["frbny:DataSet"];. Of course, the details of how you access your JSON data will change given the format of your XML and the exact stylesheet you used. Play around. If you look at the raw JSON file you can see the field names you need to use.

Bonus round: Updating the JSON. If your data changes often (like currency data does), you can put the above steps into a script and run it on a schedule. The next time your webpage is loaded, it will get the new JSON data.

Parting thoughts

JSON is a really easy way to exchange data – just think of it as including extra javascript files in your program. Read more at json.org, learn it, and love it. Good luck.




Get the Math, BetterExplained ebook

Like the site? Take it with you. Develop your math sense using insights, not memorization.

21 Comments »

Trackbacks & Pingbacks

  1. Pingback by the jackol’s den » Using JSON to Exchange Data - Mikhail Esteves — December 6, 2007 @ 3:58 am

  2. Pingback by Caminews » Using JSON to Exchange Data | BetterExplained — December 6, 2007 @ 8:10 am

  3. Trackback by Devolio — December 6, 2007 @ 10:41 am

  4. Pingback by warpedvisions.org » Blog Archive » JSON, a simpler explanation — December 6, 2007 @ 3:15 pm

  5. Pingback by links for 2007-12-07 « toonz — December 7, 2007 @ 4:24 pm

  6. Pingback by links for 2007-12-08 « Bloggitation — December 7, 2007 @ 5:19 pm

  7. Pingback by JSON - Elegant Approach for cross domain AJAX scripting: « Pandyan’s Tech Muse — April 30, 2008 @ 3:50 pm

  8. Pingback by Recent Faves Tagged With "specialfunction" : MyNetFaves — September 8, 2008 @ 4:05 pm


Comments

  1. For prototype users,

    
     var e = new Element('script',
    	   		{
    	   			'src': url,
    	   			'type' : 'text/javascript' 
    	}
    ); 
     $$("head")[0].appendChild(e);    
    

    Not sure about when browsers finish loading and add the files into the dom tho, there could be significant delay before objects are loaded / added using this script method…

    Simon — December 6, 2007 @ 7:09 am

  2. Hi Simon, thanks for the tip.

    Kalid — December 6, 2007 @ 10:36 am

  3. Can we combine this with Natural Language Processing to make, for once, a comprehensive browser?

    coogan — December 6, 2007 @ 1:16 pm

  4. Just a side note for these dynamic loaders: You do not need the type attribute because it is ignored when the src tag is used. The server is then relied on to give the correct mime type.

    Greg Ferrell — December 6, 2007 @ 1:48 pm

  5. @coogan: I’m not quite sure what you mean. JSON basically a programmer-friendly way to represent data.

    @Greg: Thanks for the info! I wasn’t aware of that.

    Kalid — December 6, 2007 @ 2:33 pm

  6. You don’t need to quote the name if it has no spaces.. Eg:

    var fancyFruit = {name:”pear”, color:”greenish”};

    steve — December 6, 2007 @ 7:15 pm

  7. Hi Steve, thanks for the tip; I didn’t know that either :) .

    Kalid — December 6, 2007 @ 11:12 pm

  8. Good tips. I recently had a case to need to proxy an XML file (to get around browser security) and decided I might as well convert to JSON in the process.
    There is a very good generic schema on google code.
    http://code.google.com/p/xml2json-xslt/
    Don’t use the download though. There are versions of the schema with bug fixes in the issues.

    Here’s my blog post on it if you’re interested.
    http://willcode4beer.blogspot.com/2007/12/xml-to-json.html

    Paul — December 7, 2007 @ 10:41 am

  9. “You don’t need to quote the name if it has no spaces..”

    Steve,

    Even-though in JavaScript it is unnecessary to quote object variable names, it is part of the language spec of JSON to ALWAYS do so, so in order to be compatible with all of the JSON parsers of the various languages, it is a better idea to go ahead and quote all object variable names in JSON data.

    Greg Ferrell — December 10, 2007 @ 4:34 am

  10. Ive always been interested in JSON. Im going to use it after reading this great introduction.
    Thanks

    psychic readings — December 11, 2007 @ 5:59 am

  11. This post looks interesting, thanks.

    Vasudev
    —-
    Vasudev Ram
    Dancing Bison Enterprises
    Software consulting and training
    Biz site: http://www.dancingbison.com
    Blog (on software innovation): http://jugad.livejournal.com
    Quick and easy PDF creation toolkit: http://www.dancingbison.com/products.html

    Vasudev Ram — December 11, 2007 @ 11:00 am

  12. Nice, but a bit late. I’ve ben using such a technique for quite a long time. Actualy full 10 years long – that’s a decade.

    But I never thought about giving it a name. It was simply a workaround to pass new content to div’s and I’ never managed to keep it as clean routine.

    Hope you do. :)

    aeneas dardanus — December 22, 2007 @ 2:22 am

  13. Good article. I have seen that Json can be used along with google apis which is great..

    ITGalary — January 10, 2009 @ 5:11 pm

RSS feed for comments on this post. TrackBack URI

Leave a comment

Have a question? Know an explanation that caused your own a-ha moment? Write about it here.




Like it? Try All articles, RSS Feed or Email Subscription | Idea or suggestion? Contact me
copyright © 2009 Kalid Azad