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> </code>
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")>
<h2>XML Version (#len(xmlVersion)# chars)</h2>
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)>
<h2>JSON Version (#len(jsonVersion)# chars)</h2>
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.