Quick example of JSON versus XML

If you haven't heard of JSON (JavaScript Object Notation), I think the simplest way to think of it is as a serialized form of data. Much like the old CFWDDX that few people use anymore, JSON is a way to take some data, any data, and convert it into a string. Like WDDX, you can both serialize and deserialize JSON data.

One of the benefits of JSON is that it is a lot less weightier than XML. While it isn't nearly as readable, when it comes to AJAX it has the benefit of simply shifting less bits back and forth while passing the same information.

I had not really paid much attention to JSON, but with the size issues cropping up in ColdFire, I took a look and I was really surprised by how much JSON cuts down on the size of the data. Consider the following code:

<cfset data = queryNew("id,name,age,active","integer,varchar,integer,bit")>

<cfloop index="x" from="1" to="100"> <cfset queryAddRow(data)> <cfset querySetCell(data,"id",x)> <cfset querySetCell(data,"name","User #x#")> <cfset querySetCell(data,"age",randRange(20,90))> <cfset querySetCell(data,"active",false)> </cfloop>

This creates a rather simple query of 100 rows. I'll use my toXML CFC to convert this into an XML packet and then report on the size:

<cfset xmlVersion = queryToXML(data,"people","people")> <cfoutput> <h2>XML Version (#len(xmlVersion)# chars)</h2> #htmlCodeFormat(xmlVersion)# </cfoutput>

I ended up with a string that was 7939 characters long. Now lets convert that to JSON using CFJSON from Thomas Messier.

<cfset jsonVersion = encode(data)> <cfoutput> <h2>JSON Version (#len(jsonVersion)# chars)</h2> #htmlCodeFormat(jsonVersion)# </cfoutput>

Size of the JSON packet? 1881 characters. That's pretty significant. Spry does not yet support JSON, but when/if it does, I certainly plan on switching where appropriate.

Like This?

If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can also subscribe to the email feed to get notified of new posts.