Array
University of Oregon

JSON

json-logo

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. json-card

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

  1. JSON Intro
  2. JSON Syntax Rules
  3. Mr Data Converter. Simply copy and paste from a spreadsheet to create a JSON dictionary.

Accessing JSON Fields

JSON objects are Associative Arrays (key/value pairs), a.k.a. hashes:

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

  1. 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

  2. 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

CIT 281 Preview: These methods are useful when passing data to and from a web server using Ajax requests or when using localStorage (e.g., files, Redis, MongoDB) to store data on a user s machine.

Mr Data Converter

Typing JSON into a code editor is tedious and error-prone. Mr Data Converter is worth a bookmark.

JSON vs XML

JSON is sometimes called, XML-lite.

Note that, to process an XML document, JavaScript must first convert the XML to JavaScript. JSON requires no such conversion.

Skip to toolbar