At Code Camp last weekend, I attended a session on the Spark View Engine for ASP.NET MVC (which was just released under the MS-PL!). Actually, there were a lot of things I liked about the look of Spark, and I might consider using it on future projects. I plan to talk a little more about Spark later, but this post is more about something I heard time and again from the Presenter, which, while I understand why he was saying it, I consider to be a dangerous mistake in that it promotes dangerous thinking.
The thing that bothered me when he started talking about handling JSON data. The example he presented involved a simple table of names that could be updated dynamically via JavaScript, essentially he'd send JSON data which would be used to build new table rows. The JSON data resembled the following:
[ { firstName: "Bill", lastName: "Paxton" }, { firstName: "John", lastName: "Doe" }, { firstName: "Malcolm", lastName: "Reynolds" } ]
The problem I had, was that he kept referring to the JSON data as "JavaScript".
Okay, I know that JSON is short for the JavaScript Object Notation. I know that JSON can be eval'd inside of a JavaScript engine to result in the data object that it represents. But, JSON is not JavaScript. And thinking that is such is incredibly dangerous.
Why is JSON not JavaScript? For one, the JSON Specfication does not allow code. It is a pure data format. For another, while JSON may have originally been borne out of the JavaScript world, it has grown into a common data representation used for data transfer from any number of languages. But most importantly, executing JSON without verifying it follows the specification is amazingly dangerous. There is a reason why all the major JavaScript frameworks I'm aware of offer special JSON parsers. JSON is data, and treating it as code opens you up to any number of attack vectors.
JavaScript is a Programming Language. JSON is merely a data format. Yes, JSON is a subset of JavaScript, but it is far more strict than JavaScript is. Use a library to parse your JSON, instead of just eval'ing it, and remember to keep a strong mental distinction between your code and your data. Just because they might resemble each other, doesn't mean you should treat them the same.