CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Jay Kimble -- The Dev Theologian

Philosophizing about the .Net religion

JSON and AJAX

[Ok, Jeremy, requested a fuller post on JSON, so I thought I would comply, and try to do the brain dump].

As mentioned before, I  recently ran into some compatibility issues; specifically with the Mac.  My JAAJAX Library as you all know uses pure XML because… hey, it’s XML… XML rules! (just call me JayXML… although that nickname might be trademarked <grin />).  Seriously, XML is great for transferring data between systems.  So it seemed like the perfect answer for AJAX (note: that the X is for XML).

So when everything broke on the Mac it was back to the drawing board.  I put my career on the line with this code, it had better work… (My boss had recommended Ajax.Net)

Ok, so I ended up at Apple’s Developer’s site (a place I know too well for my own comfort).  There was a reference to JSON on the site.  So if you clicked the link you came to the very cryptic looking description of the format.  As mentioned before it’s really not that hard to understand, but the presentation really stinks.  Let’s try a different link… Take a look at the JSON in Javascript link.  Now it’s real clear, hunh? (I’m doing the brain dump… part of the dump is getting you to where I got).

Ok, enough surfing. let’s start looking at the format a little better (don’t worry I’ll tell you how to use it with AJAX).

Examples

In my case I have a simple object that I want to return.  It looks like this

JAAJAX Return Object
Error Property – String
ReturnValue Property – ?? (this could be a string, it could be an int, it might be an object)

So to see this in action.  Let’s assume that we want to return a string in the return value property.  The JSON string looks like this:
{"Error":"", "ReturnValue":"My String"}

That’s probably not too hard.  Let me break that down. The curly braces tell javascript that this is an object with properties only (you can’t give it code), so this is more like a classic c struct or a VB Type or… well you probably get it… there’s no code here, just data.  Now let’s break things apart at the comma.  Which gives us two items:
"Error":""
"ReturnValue":"My String"
Again this isn’t too hard.  The colon separates the property name and it’s value. So Property Error="" (which is good no error), and the ReturnValue="My String" (also good we have a return value).

Ok, that was easy.  So let’s do something a little more complex.  Let’s say that we want to have that ReturnValue property actually return some kind of object.  Here’s a real world scenario.  This return value is the result of a call that is populating a database table and we need to get an success True/False and the new id if it was successful, so the ReturnValue is going to be an object with a WasSuccessful property and a NewId property.  Here’s the JSON (BTW, this is all coming off the top of my head, so someone will need to test… maybe me.. Ok, before publishing I did test… my code was fine, BlogJet introduce the fancy quotes which screwed me up.)
{"Error":"", "ReturnValue": {"WasSuccessful":true, "NewId":1001} }

Alright so I can skip over to the ReturnValue, see that it’s value is contained within curly braces?  That means that ReturnValue is an object and it will return a complex value.  The only real differences with this object is that we aren’t returning strings.  The first property is a boolean (well, actually it contains the boolean true value) and then second property is a number). 

So now you see by nesting you can build some pretty crazy constructs.  But what about arrays?  Well, now the fun begins!  Arrays are signified by Square Brackets, so let’s return some ints.  Here’s the JSON:
{"Error":"", "ReturnValue":[ 1, 2, 3 ] }

Not sure an explanation is needed, but we are returning an array of 3 numbers to the ReturnValue Property.  Let’s do something useful like return an array of option-like objects.  An option object for a select box contains a text property and a value property.  So that looks like this:
{"Error":"", "ReturnValue":[ { "text":"My Text", "value":1 }, { "text":"My Text2", "value":2 } ] }

I’m done explaining at this point… just look at the last two examples; this last one combines them both (it’s an array where each element contains an object).

Implementation in an AJAX world

Ok, so how do you take JSON string and reconstitute it as an object.  It’s drop dead simple:
var MyObject = eval(JSONString);

Yep, the eval function works great.  There’s another option I discovered (on another site which I’ve lost the URL to)
var MyObject = new Function("return " + valueString)();

This both creates a temporary function that returns the object and executes it in one shot.  This will protect you somewhat from a string that you don’t trust 100% (like one coming from a different server than the one the original page is from).  The upcoming release of JAAJAX will use this method for code safety.

So on the server you really have just a couple things you have to do:

  1. Set the content type to application/json (like this in ASP.Net C# syntax – Response.ContentType = "application/json";)
  2. Return only the JSON string

Yes, this means that it’s not really XML coming down, So you want the responseText property of the xmlHttpRequest object and not the responseXML.


After Blog Mint - I know I don't do these often, but I thought I should mention that have been playing with Thycotic's cool Secret Server. They just released their 1.1 version. It's free for a single user. It's a web site, BTW, that you can use it to store all kinds of secrets like password, account numbers, etc.



Check out Devlicio.us!

This Blog

Syndication

News

CodeBetter.Com Home
Current Threat level
Terror Alert Level