Tuesday, September 2, 2014

Choosing a data format for Javascript

HTML snippets require very little work to implement. The external data can be loaded
and inserted into the page with one simple method that does not even require a
callback function. No traversal of the data is necessary for the straightforward task
of adding the new HTML into the existing page. On the other hand, the data is not
necessarily structured in a way that makes it reusable for other applications. The
external file is tightly coupled with its intended container.

JSON files are structured for simple reuse. They are compact and easy to read. The
data structure must be traversed to pull out the information and present it on the
page, but this can be done with standard JavaScript techniques. Since modern
browsers parse the files natively with a single call to JSON.parse(), reading in a
JSON file is extremely fast. Errors in the JSON file can cause silent failure or even
side effects on the page, so the data must be crafted carefully by a trusted party.

JavaScript files offer the ultimate in flexibility, but are not really a data storage
mechanism. Since the files are language-specific, they cannot be used to provide
the same information to disparate systems. Instead, the ability to load a JavaScript
file means that behaviors that are rarely needed can be factored out into external
files, reducing code size unless and until it is needed.

While XML has fallen out of favor in the JavaScript community, with most developers
preferring JSON, it is still so common that providing data in this format makes it very
likely that the data can be reused elsewhere. Indeed, many web services, such as Yahoo
Weather (http://developer.yahoo.com/weather/), export XML representations
of their data, which has allowed many interesting mashups of their data to arise. The
XML format is somewhat bulky, and can be a bit slower to parse and manipulate than
other options.

No comments:

Post a Comment