XML and JSON

by Castwide on 11-27-2008 • Tags: json, xml0 comments

I've been looking into an alternative method for serializing data in PHP instead of the serialize() and unserialize() functions. Those functions are fine for serializing objects, but I wanted to find a solution that was more portable for simple data. Two obvious answers are XML and JSON, but I wasn't sure which made more sense for this particular scenario. While looking for insight, I ran across this article on Ajaxian.

I especially enjoyed the discussion on Dave Winer's blog, part of which Ajaxian quoted. In response to Winer's complaints about JSON reinventing the wheel, Douglas Crockford retorted, "The good thing about reinventing the wheel is that you can get a round one." I'm a big fan of Crockford.

The first comment on Ajaxian makes an excellent point:

I believe that the most important thing to understand in the JSON and XML debate is that they are really fundamentally built for two distinct purposes. XML is built for giving semantic meaning two [sic] text within documents. JSON is built for data structures.

Simon Willison's comment on Dave Winer's blog goes into more detail:

Counter to what almost everyone here has said, JSON isn’t just for JavaScript. I frequently use it to move data from PHP applications to Python applications - and it’s by far the best tool for that job. If you have structured data in one place (by structured I mean strings, associative arrays and lists) and want to move it somewhere else you need some kind of cross-platform serialization format. XML isn’t one - you have to invent your own format using XML first. XML-RPC and SOAP almost solve this problem but come with extra baggage - they are full-blown RPC mechanisms with transports, when I just need a serialization format. JSON hits a really nice sweet spot - it’s simple, human readable, efficient and has libraries in all of the languages I care about.

XML is a great tool for some jobs, but in my experience sending a simple list of strings from one place to another is a lot less painful with JSON.

A blog entry on Simon's web site explains further.

The particular scenario for which I need serialization is storing plugin configurations in Phrameworks. The configuration data is stored in an array of strings, numbers, and arrays. JSON seems to be the best solution here, because it has a native syntax for serializing arrays. XML can obviously store arrays of data, but representing an empty array or an array with a single element gets a little hairier. JSON automatically handles those cases. PHP's JSON functions also make it just as easy to handle JSON data as it is to serialize objects.

There are many other scenarios where XML would seem a better solution, so any debate about which one is better in the general case seems counterproductive. It's the difference between a hammer and a screwdriver.

There are no comments posted to this news item.

Add Comment

More Articles