PROWARE technologies
PROWARE technologies

JavaScript Tutorial

JSON

JSON, JavaScript Object Notation, is a data format and not a programming language.

Syntax

Objects

The difference between JavaScript strings and JSON strings is that JSON must use double quotes to be valid.

A JavaScript object literal looks like this:

var object = {
	name: "Dave",
	age: 39
};

This is the same as the previous example.

var object = {
	"name": "Dave",
	"age": 39
};

Now in JSON.

{
	"name": "Dave",
	"age": 39
}

You can embed objects within objects.

{
	"name": "Dave",
	"age": 39,
	"address": {
		"street": "123 Abc Ln.",
		"city": "Austin",
		"state": "Texas",
		"country": "United States"
	}
}

Arrays

This is an array in JSON.

[42,"hello",false]

This is an array in JavaScript (very similar).

var arrayObj = [42,"hello",false]; 

Arrays and object can be used together.

[
	{
		"title": "Professional ASP.NET MVC 1.0",
		"authors": [
			"Rob Conery",
			"Scott Hanselman",
			"Phil Haack",
			"Scott Guthrie"
		],
		edition: 1,
		year: 2011
	},
	{
		"title": "Professional ASP.NET MVC 2.0",
		"authors": [
			"Jon Galloway",
			"Rob Conery",
			"Scott Hanselman",
			"Phil Haack",
			"Scott Guthrie"
		],
		edition: 1,
		year: 2012
	},
	{
		"title": "Professional ASP.NET MVC 3.0",
		"authors": [
			"John Galloway",
			"Brad Wilson",
			"Phil Haack",
			"K. Scott Allen"
		],
		edition: 1,
		year: 2013
	},
	{
		"title": "Professional ASP.NET MVC 4.0",
		"authors": [
			"John Galloway",
			"Brad Wilson",
			"Phil Haack",
			"K. Scott Allen"
		],
		edition: 1,
		year: 2014
	}
]

JSON Object

The JSON object has two methods, stringify() and parse().

var person = {
			lastname: "Hughes",
			firstname: "John",
			relatives: [
				"JoAnn Hughes"
				"Jim Hughes"
				"Simon Hughes"
			],
			street: "123 Abc Ln.",
			city: "Austin",
			state: "Texas",
			zip: "78705"
		};
var JsonString = JSON.stringify(person); // strip all the white space out

This example serializes a JavaScript object into a JSON string.

A JSON string can be passed directly into JSON.parse() and it creates a JavaScript value. To create an object similar to the person object:

var personObj = JSON.parse(JsonString);

Filtering Results

If the second argument to JSON.stringify() is an array, then it will include only object properties that are listed in the array.

var person = {
			lastname: "Hughes",
			firstname: "John",
			relatives: [
				"JoAnn Hughes"
				"Jim Hughes"
				"Simon Hughes"
			],
			street: "123 Abc Ln.",
			city: "Austin",
			state: "Texas",
			zip: "78705"
		};
var JsonString = JSON.stringify(person, ["street", "city", "state", "zip"]); // create a JSON string with just the address
<< < [Page 21 of 22] > >>
Contact