Thursday, October 8, 2009

Intro to JSON

This is a simple intro to getting started with JSON.

JSON stands for Java Script Object Notation; it is a native format to the JavaScript engine that makes it possible to create simple (or complex) data structures. Lets take a look at a very simple JSON object.

var MyObject = { "name" : "Bob" };

As you can see, this is a very simple example, but let's take a look at how we can make use of this simple JSON structure.


That will return the value "Bob". Lets try adding a few more details to our JSON object and see how we can access these values.

var MyObject = { "name" : "Bob", "title" : "Manager", "phone" : "415-555-1212" };

Now lets try to access these values.


The values returned are:

Pretty straight forward right? Lets now use these values by concatenating them into a string.

var StringExample = "Hi, my name is " + + ". My job title is " + MyObject.title + ", and my phone number is " +;

Now call that variable to print out the string.


You should now see:
Hi, my name is Bob. My job title is Manager, and my phone number is 415-555-1212

You're probably now asking "What if I need to make a structure that contains more than one record?". We have a simple solution for doing just that utilizing arrays. Lets take a look.

var MyObject = {"people" : [ {"name" : "Bob"},{"name" : "Steve"}, {"name" : "Joe" }]};

Lets print out the first name value in our "people" array.


The value that we should get is:

Let's look at the next value:


The value that we should get is:

Lets now loop through our array and get all of the values.

for (var i=0; i < MyObject.people.length; i++) {

You should see all of the name values in your array printed out.

Let's add a few more values to our array just to be clear that we have a good understanding of how to utilize this structure.

var MyObject = {
"people" : [
{"name" : "Bob", "title" : "Manager", "phone" : "415-555-1212" },
{"name" : "Steve", "title" : "Programmer", "phone" : "415-555-4545" },
{"name" : "Joe", "title" : "Secretary", "phone" : "415-555-9999" }

Now lets print the "title" of the first element in our "people" array.


You should get the value:

Now lets print the "phone" of the third element in our "people" array.


You should see the value:

So that's JSON in a nutshell. There are obviously more complex ways to utilize JSON, but hopefully this gets you started on the right path and you find JSON to be a useful structure for simplifying your code.

No comments:

Post a Comment