JSON Syntax (Cont.)
JSON Values
In JSON, values must be one of the following data types: (i) a string, (ii) a number, (iii) an object, (iv) an array, (v) a boolean, and (vi) null
.
In JavaScript values can be all of the above, plus any other valid JavaScript expression, including: (i) a function, (ii) a date, and (iii) undefined
.
In JSON, string values must be written with double quotes:
In JavaScript, you can write string values with double or single quotes:
{ name: 'John' } // JavaScript
|
JavaScript Objects
Because JSON syntax is derived from JavaScript object notation, very little extra software is needed to work with JSON within JavaScript.
With JavaScript you can create an object and assign data to it, like this:
person = { name:"John", age:31, city:"New York" }; // JavaScript
|
You can access a JavaScript object like this:
person.name; // JavaScript: returns John
|
It can also be accessed like this:
person["name"]; // JavaScript: returns John
|
Data can be modified like this:
person.name = "Gilbert"; // JavaScript
|
It can also be modified like this:
person["name"] = "Gilbert"; // JavaScript
|
JavaScript objects and arrays can be written as JSON.
For a JSON file,
- the file type is
.json
, and
- its MIME type is
application/json
.
Demonstration
The following demonstration shows how the script of HTML and JavaScript is displayed on the Web.
Why are there interstate highways in Hawaii?
― Steve Wright
|