JavaScript Object Notation (JSON)
JSON was invented by Douglas Crockford in 2001, and is a subset of object literal notation.
The JSON specification is so short and simple that Crockford created business cards with the whole JSON grammar on their back.
There are two essential differences between object literals and JSON: Property names must be double-quoted strings, and functions cannot be used as values (i.e., no methods).
JSON is used for data serialization (think stringify) to exchange information between web servers and clients. JSON is the de facto standard format for data exchange between web servers, clients and mobile apps.
JSON hits the sweet spot between being both human- and machine-readable.
Learning JSON
Accessing JSON Fields
JSON objects are Associative Arrays (key/value pairs), a.k.a. hashes, as in, hashing keys to values:
var NATO = {
“a”: “Alpha”,
“b”: “Bravo”,
“c”: “Charley”,
“d”: “Delta”,
“e”: “echo”,
“0”: “Zero”,
“1”: “Wun”,
“2”: “Two”
};console.log(NATO.a);
console.log(NATO[“a”]);
console.log(NATO[a]); //ReferenceError– a is not defined
JSON Methods
- JSON.parse. Converts a string (text) into a JSON object (binary).
//Note: quote swapping
var s = ‘{“first_name”:”Argus”, “last_name”:”Filch”}’;
var obj = JSON.parse(s);console.log(s.first_name); //error– strings do not have first_name property
console.log(obj.first_name); //OK
console.log(obj[“first_name”]; //OK - JSON.stringify. Converts a JSON object (binary) into a string (text). Strings can be easily sent across the Internet, binary objects are a lot more work. This is what is meant by data serialization.
var obj = {“first-name”:”Argus”, “last-name”:”Filch”};
var s = JSON.stringify(obj);console.log(obj.first_name); //OK
console.log(obj.indexOf(“A”)); //error– JSON does’t have indexOf property
console.log(s.indexOf(“A”)); //OK
These methods are useful when passing data to and from a web server using Ajax requests or when using a data store (e.g., files, localStorage, databases, etc.) to store data on a user’ s machine.
Optional JSON
- JSON is sometimes called XML-lite. To process an XML document, JavaScript must first convert the XML to JavaScript. JSON requires no such conversion.
- Mr Data Converter. Converts Excel data into JSON.