JSON

JavaScript Object Notation (JSON) is a lightweight data format based on the object notation of the JavaScript language. Unlike XML, JSON is already JavaScript so it does not have to endure heavy processing. Because of its ease of use and flexibility to exchange data, it has gained popularity. If you are thinking of using JSON, I would recommend you check out the web site (http://json.org).

Example 5-7 shows a simple JSON structure.

Example 5-7. An example of JSON notation

{
    "type": "Menu",
    "value": "File",
    "items": [
        {"value": "New", "action": "CreateNewDocument"},
        {"value": "Open", "action": "OpenDocument"},
        {"value": "Save", "action": "SaveDocument"}
    ]
}

JSON was designed to be highly portable. It's what makes it useful. JSON output text can be directly interpreted by JavaScript, using eval( ):

var myVar = eval( '(' + jsontext + ')' );

Validation and implementation

Passing JSON text straight into the eval( ) function is a bit like setting a bull loose in a china shop, since eval( ) will blindly interpret everything in the JSON text with no security or validation checking, but boy is it fast. So, what's wrong with automatically hydrating this stuff? The most obvious attack is XSS. Consider what would happen if the code in Example 5-7 were run through eval( ).

Example 5-8 shows XSS in JSON.

Example 5-8. Unvalidated JSON

{ "name": "menu", "value": "File", "items": [ {"value": "New", "action": "CreateNewDocument"}, {"value": "Open", "action": "OpenDocument"}, {"value": "Save", "action": ...

Get Securing Ajax Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.