What is JSON?

Written by Tony Lea on Mar 23rd, 2011 Views Report Post

I'm sure if you are a web developer you have probably heard of the word JSON or JSON array. Don't be scared about the word, it's actually very simple, and just because I have to say it... It stands for Javascript Object Notation. Hope that didn't scare you, because that is probably one of the hardest things to remember about JSON, which is what it stands for.

Okay, so onto understanding JSON in a few paragraphs. JSON is basically a javascript text structure (think of it similar to XML, which is also just a text structure) so this structure is easily readable and writable across most technologies. PHP and Javascript for example. So, to create a simple javascript array using this structure would look like the following:

var jsonArray = { 
		"firstName" : "Tony",
		"lastName"  : "Lea",
		"isAwesome" : "Yes" 
	};

That's it... A simple JSON array. Now to retrieve this data in Javascript you would simply do the following:

jsonArray["firstName"]     // contains 'Tony'
jsonArray["lastName"]      // contains 'Lea'
jsonArray["isAwesome"]   // contains 'Yes'

Ok, you're probably with me so far; however, you are not really seeing anything to impressive. Well, let's change that, here is a sample JSON Array: (similar to the one above)

var jsonArray = { employees: 
	[ { "firstName" : "Tony",
		"lastName"  : "Lea",
		"isAwesome" : "Yes" },
	{ "firstName" : "John",
		"lastName" : "Doe",
		"isAwesome" : "Yes" } 
	]};

Now, we have just added an array of 2 employees. And to display this data we can simply incorporate object notation as follows:

jsonArray.employees[0].firstName    // this will contain 'Tony'
jsonArray.employees[1].firstName    // this will contain 'John'

Very cool, right? I'm sure you can see that you will be able to loop through the JSON array and print out all or multiple 'employee' data.

Plus note: encoding arrays into JSON from multiple languages is very simple. For example to 'encode' a PHP array into a JSON array:

json_encode($array);

That's all you have to do in PHP, now you can easily pass that array to Javascript and easily get and use the new JSON array. This is just a simple example of using JSON arrays in Javascript. For further reading about how to use JSON, you can follow the following resources:

Comments (0)