Web Programming Step by Step, 2nd Edition

Lecture 24: JavaScript Object Notation (JSON)

Reading: 12.4

Except where otherwise noted, the contents of this document are Copyright 2012 Marty Stepp, Jessica Miller, and Victoria Kirst. All rights reserved. Any redistribution, reproduction, transmission, or storage of part or all of the contents in any form is prohibited without the author's expressed written permission.

Valid HTML5 Valid CSS

Pros and cons of XML

An example of XML data

<?xml version="1.0" encoding="UTF-8"?>
<note private="true">
	<from>Alice Smith (alice@example.com)</from>
	<to>Robert Jones (roberto@example.com)</to>
	<to>Charles Dodd (cdodd@example.com)</to>
	<subject>Tomorrow's "Birthday Bash" event!</subject>
	<message language="english">
		Hey guys, don't forget to call me this weekend!
	</message>
</note>

JavaScript Object Notation (JSON)

json
json

JavaScript Object Notation (JSON): Data format that represents data as a set of JavaScript objects

Background: Creating a new object

var name = {
	fieldName: value,
	...
	fieldName: value
};
var pt = {
	x: 4,
	y: 3
};
pt.z = -1;
alert("(" + pt.x + ", " + pt.y + ", " + pt.z + ")");   // (4, 3, -1)

More about JavaScript object syntax

var person = {
	name: "Philip J. Fry",                           // string
	age: 23,                                         // number
	"weight": 172.5,                                 // number
	friends: ["Farnsworth", "Hermes", "Zoidberg"],   // array
	getBeloved: function() { return this.name + " loves Leela"; }
};
alert(person.age);                                 // 23
alert(person["weight"]);                           // 172.5
alert(person.friends[2]));                         // Zoidberg
alert(person.getBeloved());                        // Philip J. Fry loves Leela

Repeated: Example XML data

<?xml version="1.0" encoding="UTF-8"?>
<note private="true">
	<from>Alice Smith (alice@example.com)</from>
	<to>Robert Jones (roberto@example.com)</to>
	<to>Charles Dodd (cdodd@example.com)</to>
	<subject>Tomorrow's "Birthday Bash" event!</subject>
	<message language="english">
		Hey guys, don't forget to call me this weekend!
	</message>
</note>

The equivalant JSON data

{
	"private": "true",
	"from": "Alice Smith (alice@example.com)",
	"to": [
		"Robert Jones (roberto@example.com)",
		"Charles Dodd (cdodd@example.com)"
	],
	"subject": "Tomorrow's \"Birthday Bash\" event!",
	"message": {
		"language": "english",
		"text": "Hey guys, don't forget to call me this weekend!"
	}
}

Valid JSON

var student = {                            // no variable assignment
	"first_name": 'Bart',                    // strings must be double-quoted
	last_name: "Simpson",                    // property names must be quoted
	"birthdate": new Date("April 1, 1983"),  // Date objects not supported
	"enroll": function() {                   // Functions not supported
		this.enrolled = true;
	}
};

Browser JSON methods

method description
JSON.parse(string) converts the given string of JSON data into an equivalent JavaScript object and returns it
JSON.stringify(object) converts the given object into a string of JSON data (the opposite of JSON.parse)

JSON expressions exercise

var data = JSON.parse(this.responseText);
{
	"window": {
		"title": "Sample Widget",
		"width": 500,
		"height": 500
	},
	"image": { 
		"src": "images/logo.png",
		"coords": [250, 150, 350, 400],
		"alignment": "center"
	},
	"messages": [
		{"text": "Save", "offset": [10, 20]},
		{"text": "Help", "offset": [ 0, 50]},
		{"text": "Quit", "offset": [30, 15]}
	],
	"debug": "true"
}

Given the JSON data at right, what expressions would produce:

var title = data.window.title;
var coord = data.image.coords[2];
var len = data.messages.length;
var y = data.messages[len - 1].offset[1];

JSON example: Books

Suppose we have a service books_json.php about library books.

JSON exercise

Write a page that processes this JSON book data.

Working with JSON book data

function showBooks() {
	// add all books from the JSON data to the page's bulleted list
	var data = JSON.parse(this.responseText);
	for (var i = 0; i < data.books.length; i++) {
		var li = document.createElement("li");
		li.innerHTML = data.books[i].title + ", by " +
				data.books[i].author + " (" + data.books[i].year + ")";
		document.getElementById("books").appendChild(li);
	}
}

Bad style: the eval function

// var data = JSON.parse(this.responseText);
var data = eval(this.responseText);   // don't do this!
...