JSON

To users of dynamic and/or scripting languages like Python, JavaScript, Ruby, Lua, and many more, the JavaScript Object Notation (or JSON) is almost second nature. It is a natural way of expressing integers, strings, lists, and mappings (a.ka. dictionaries, hashes, objects).

In JavaScript…

In JavaScript, the format actually runs! We can simply call eval():

Evaluating JSON strings:

var tree = eval('({"type": "addition", "children": [{"type": "integer", "val": 5}, {"type": "multiplication", "children": [{"type": "integer", "val": 3}, {"type": "integer", "val": 2}]}]})');

Just a javascript object:

{
    "type": "addition", 
    "children": [
        {
            "type": "integer", 
            "val": 5
        }, 
        {
            "type": "multiplication", 
            "children": [
                {
                    "type": "integer", 
                    "val": 3
                }, 
                {
                    "type": "integer", 
                    "val": 2
                }
            ]
        }
    ]
}

However, for security reasons, json2.js is preferred.

Keep in mind that in JavaScript at least, navigating a JSON structure is the same as navigating a pile of objects. It can be a little tedious. We’re really just chasing references down the structure that we’ve defined. For example:

tree.children[1].children[0].type

It’s just javascript, but we’ll see that finding items in trees is a common problem. Now let’s look at some techniques for doing this in XML.

XPath

XML & XPath Tools

XPath in Other Programming Languages