The most efficient data transmission formats use a minimal number of structural elements to delimit the data. Consider our book data in XML and JSON. We’re always expecting six items of data per book, so we could simply use a format such as:
The Principles of Beautiful Web Design, 2nd Edition;https://www.sitepoint.com/books/design2/;Jason Beaird;SitePoint;39.95;USD jQuery: Novice to Ninja;https://www.sitepoint.com/books/jquery1/;JEarle Castledine & Craig Sharkie;SitePoint;29.95;USD Build Your Own Database Driven Website;https://www.sitepoint.com/books/phpmysql4/;Kevin Yank;SitePoint;39.95;USD
Essentially, our data is similar to comma-separated list. We’ve used carriage returns to delimit books and semi-colons to delimit individual data items (commas couldn’t be used because they appear in book titles and possibly numeric values). Choosing the right data delimiters is the most important decision we have to make.
A custom data format offers several advantages:
- It’s the most lightweight format and will result in faster Ajax responses.
- The data can be generated quickly by any server-side language without additional formatting libraries.
- It’s not easy to create a malicious payload.
But note the disadvantages:
- This may not be a viable solution if the number of object properties are inconsistent. For example, assume our books had optional PDF URLs or prices in multiple currencies. We may require further delimiters and our parsing will become more difficult.
- Your web service may be more limited in scope than one which returns XML or JSON. This won’t be an issue if you’re writing services for your own applications but it’s something to consider if you intend publishing the data for third parties.
- A custom parser must be written for every type of data response.
- The data is not necessarily human-readable.
- You must be absolutely certain that delimiter characters do not appear in the original data. You could check for their existence or consider using delimiters toward the start of the ASCII character set.
I hope this series of articles has given you a number of Ajax data formatting options to consider. Have you used any other data formats?
Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.