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.
<?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): Data format that represents data as a set of JavaScript objects
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)
z)
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
this.fieldName or ["fieldName"] syntaxweight above)<?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>
{
"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!"
}
}
var student ={ // no variable assignment "first_name":'Bart', // strings must be double-quotedlast_name: "Simpson", // property names must be quoted "birthdate":new Date("April 1, 1983"), // Date objects not supported "enroll":function() {// Functions not supportedthis.enrolled = true;}};
JSON has a few rules that differ from regular JS:
Function, Date, RegExp, ErrorNumber, String, Boolean, Array, Object, null| 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.parse on it to convert it into an objectvar 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];
Suppose we have a service books_json.php about library books.
{ "categories": ["computers", "cooking", "finance", ...] }
category query parameter to see all books in one category:
{
"books": [
{"category": "cooking", "year": 2009, "price": 22.00,
"title": "Breakfast for Dinner", "author": "Amanda Camp"},
{"category": "cooking", "year": 2010, "price": 75.00,
"title": "21 Burgers for the 21st Century", "author": "Stuart Reges"},
...
]
}
Write a page that processes this 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);
}
}
eval function// var data = JSON.parse(this.responseText); var data = eval(this.responseText); // don't do this! ...
eval keyword that takes a string and runs it as codeJSON.parse does,JSON.parse filters out potentially dangerous code; eval doesn'teval is evil and should not be used!