Tech Tuesday: Data Structures (JSON)
In today’s Tech Tuesday we are continuing our romp through Data Structures as part of the ongoing series on programming by looking at JSON. Now technically JSON, which stands for JavaScript Object Notation, is not a data structure but a textual notation (as its name implies). But JSON has become ubiquitous and provides a natural segue to objects (next Tuesday) that I figured it makes sense to discuss it here.
Sticking with the example of points, the JSON for a point might look like the following
{
"x" : 2,
"y" : 3,
"color" : {
"red" : 120,
"green" : 20,
"blue" : 200,
}
}
In this example instead of a single string for a color (“blue”) as before, I am showing how JSON lets us describe levels of nesting. The red, green and blue are sub-attributes of the color attribute.
How would we actually use this JSON? In modern implementations of JavaScript, we can make a direct assignment of JSON to a variable as follows:
var point = { <JSON from above> };
print(point.x);
print(point.color.green);
You can see this code running here. The variable point now holds the attributes that we described in easily human readable form in JSON. We access these attributes in the code using the dot notation shown above.
This simple example raises a bunch of questions. First, how does JavaScript implement this? JavaScript parses the text. We will learn what parsing is in more detail in the future but for now suffice it to say that it essentially means turning the text into a data structure. Which data structure? Well depending on how you look at it either as an associative array or an object. Huh? Yes, under the hood it is an associative array for sure and JavaScript even supports notation that makes this clear: instead of point.x we can write point[“x”]. But most JavaScript code that you will see uses the point.x notation instead which represent viewing point as an object. What makes an object special? That will be the subject of next Tuesday’s post.
Before that though a few more words about JSON. Because it is a textual notation, it is ideally suited for passing structured data between different programs independent of programming language. That is why many modern APIs (Application Programming Interface) consume and return JSON. Most languages require an explicit invocation of a parser to turn the JSON into a native data structure for that language which could be an associative array or something else (e.g., an object — in most languages there is a stronger distinction between the two than in JavaScript).
Posted: 25th September 2012 – Comments
Tags:
tech tuesday programming data structures JSON

