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.

document.write(MyObject.name);

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.

document.write(MyObject.name);
document.write(MyObject.title);
document.write(MyObject.phone);

The values returned are:
"Bob"
"Manager"
"415-555-1212"

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

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

Now call that variable to print out the string.

document.write(StringExample);

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.

document.write(MyObject.people[0].name);

The value that we should get is:
"Bob"

Let's look at the next value:

document.write(MyObject.people[1].name);

The value that we should get is:
"Steve"

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

for (var i=0; i < MyObject.people.length; i++) {
document.write(MyObject.people[i].name);
}

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.

document.write(
MyObject.people[0].title);

You should get the value:
"Manager"

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

document.write(
MyObject.people[2].phone);

You should see the value:
"415-555-9999"

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