JSON (JavaScript Object Notation)

JSON is written with a TEXT based JavaScript Object Notation that is used to STORE or EXCHANGE data. It is important to note that JSON is NOT an OBJECT—it is a JavaScript Object NOTATION which is simply text. However, it may be stored as an object (var myObject = JSON (JavaScript Object Notation).

Because JSON is text, it can be read and used as a data format by any programming language which makes it language independent.

IMPORTANT NOTE: There is no such thing as a JSON object. It is not an object but a STRING.,

When exchanging data between a browser and a server, the data must be text, so JSON is an ideal solution to accomplish this task:

JSON Syntax

The JSON syntax is a VERY SIMILAR to a JavaScript Object syntax, hence, its name. Data is created as name/value (or sometimes called key/value) pairs separated by a colon with each name/value pair separated by a comma and all name/value pairs within a set of curly braces:

{"name1" : value1, "name2" : value2,"name3" : value3}

JavaScript Framework

The window.onload code block method is used for convenient for each example in this tutorial:

<script>
window.onload = function(){

} // end of window.onload function
</script>

However, it is best practice to use either:

    This will allow you to use these more than once. You could also avoid using the window.onload code block by placing the code in a script tag above the closing body tag (</body>) and reference an external JavaScript file (<script src= "externalJavaScript.js"></script>). Like CSS external file (*.css), the JSON syntax is written in an external file with an *.json extension.

  1. Inside of an HTML page, create the framework for writing JavaScript code to load before the page load with a window.onload = function() code block that is inside a set of script tag.

    <script>
    window.onload = function(){

    } // end of window.onload function
    </script>
  2. Write the following JavaScript object between the curly braces:

    <script>
    window.onload = function(){
    console.log("---------- JSON Syntax ------------");
    {"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"}
    } // end of window.onload function
    </script>
JavaScript Different: A name (key) can be a string, number or identifier so it may NOT be in double quotes. A value can be all of JSON types plus a function, a date, or undefined. A string can be in single or double quotes.

Assign JSON to an Object

Example Page

You can assign JSON to a object (variable):

NOTE: Besides a JavaScript object, an array can also be used to create a JSON format.

  1. Assign the JSON format to an object (var myPersonalObject) using the assignment operator (=) and close it with a semicolon (;).

    var myPersonalObject = {"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"};
  2. Write the following code to trace the result in the Console panel:

    var myPersonalObject = {"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"};
    console.log(myPersonalObject);
  3. CHECK POINT: Save the file and preview it in a browser. Then, press CTRL+SHIFT+I  to open the Console panel. You should see the following:


Access Data

You can access data from an object by using the dot syntax (object.property_name):

  1. Write the following code below the console.log statement:

    var myPersonalObject = {"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"};
    console.log(myPersonalObject); console.log(myPersonalObject.firstName + " " + myPersonalObject.lastName);
  2. CHECK POINT: Save the file and preview it in a browser. Then, press CTRL+SHIFT+I  to open the Console panel. You should see Cornelius Chopin in the Console panel.
NOTE: While the dot syntax is easier, you can ACCESS data using the array syntax (myPersonalObject["firstName"]) since JSON is treated as an array of sort.

CAUTION: Be careful NOT to use a DOT (.) which is used only by the dot syntax when attempting to use the array syntax ( myPersonalObject.["firstName"]); otherwise, you will get an error (Uncaught SyntaxError: Unexpected token [ ).

Modify Data

Data in an object can be accessed by assigning the property name a new value:

  1. Add the following highlighted code to the previous code:

    console.log(myPersonalObject);
    myPersonalObject.firstName = "Sheila";
    console.log(myPersonalObject.firstName + " " + myPersonalObject.lastName);
  2. CHECK POINT: Save the file and preview it in a browser. Then, press CTRL+SHIFT+I  to open the Console panel. You should see that it display Shela this time instead of Cornelius.

NOTE: While the dot syntax is easier, you can also be MODIFY data using the array syntax (myPersonalObject.["firstName"] = "Sheila") since JSON is treated as an array.

Send Data To Server

Example Page

Data is a JavaScript object can be converted to a JSON string using the JSON.stringify() function BEFORE it is sent to a server:

  1. Write the following code with a script tag within a window.onload code block:

    <script>
    window.onload = function(){
    console.log("------ SEND DATA ------");
    var myPersonalObject = {"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"};
    var myJSON = JSON.stringify(myPersonalObject);
    window.location = "my_json_data.php?x=" + myJSON; // [Add php file later]

    } // end of window.onload function
    </script>
  2. Write the following PHP file in the htdocs folder of the server:
    [NEED TO DO LATER]
  3. CHECK POINT: Save the file and preview it in a browser. Then, press CTRL+SHIFT+I  to open the Console panel. You should see...

CODE EXPLANATION:

Receive Data

Example Page

If data is received in a JSON format, JavaScript can use the built-in JSON.parse() function to convert a JSON formatted string into a native JavaScript object(s).

IMPORTANT NOTE: The text string has to be in the JSON format or you will receive an error.
  1. Write the following HTML in the body:

    <h1 id="myData">This phrase will be replaced with dynamic content later.</h1>
  2. Write the following highlighted code within a script tag and within a window.onload code block:

    IMPORTANT NOTE: Notice that a JavaScript object is wrapped in a set of SINGLE quotes to SIMULATE a JSON string from a server.

    <script>
    window.onload = function(){
    console.log("------ RECEIVE DATA ------");
    var myPersonalObject = '{"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"}';
    console.log("-------------- Receive Data ------------");
    console.log(myPersonalObject);
    var myObject = JSON.parse(myPersonalObject);
    document.getElementById("myData").innerHTML = myObject.firstName + " " + myObject.lastName;

    } // end of window.onload function
    </script>
  3. CHECK POINT: Save the file and preview it in a browser. You should see Cornelius Chopin on the page as a h1 tag. Then, press CTRL+SHIFT+I  to open the Console panel. You should see the LITERAL STRING ({"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"}) because the JavaScript object was enclosed in single quote to make it a string.

Exceptions

EXAMPLE: Open the receive_data.html file created earlier and save it as receive_data_with_date.html, make the following highlighted changes and then preview result in browser.

EXAMPLE PAGE

<script>
window.onload = function(){
console.log("------ RECEIVE DATA WITH DATE ------");
var myPersonalObject = '{"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor", "startDate":"12-12-12"}';
console.log(myPersonalObject);
var myObject = JSON.parse(myPersonalObject);
myObject.startDate = new Date(myObject.startDate);
document.getElementById("myData").innerHTML = myObject.firstName + " " + myObject.lastName + "<br>" + myObject.startDate;
} // end of window.onload function
</script>

Alternatively, the optional second parameter of the JSON.parse() called reviver which is a function can be used to check each property before returning a value.

Delete the highlighted strikethrough line and and the other hightlighted lines.

<script>
window.onload = function(){
console.log("------ RECEIVE DATA WITH DATE------");
var myPersonalObject = '{"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor", "startDate":"12-12-12"}';
console.log(myPersonalObject);
var myObject = JSON.parse(myPersonalObject, function (key, value) { myObject.startDate = new Date(myObject.startDate);
if (key == "startDate") {
return new Date(value);
} else {
return value;
}
}); // End of if statement

document.getElementById("myData").innerHTML = myObject.firstName + " " + myObject.lastName + "<br>" + myObject.startDate;
} // end of window.onload function
</script>

Store And Retrieve Data Locally

Example Page

When storing and retrieving data locally, the text format is a common format to use.

  1. Write the following highlighted code within a script tag and within a window.onload code block:

    <script>
    window.onload = function(){
    var myPersonalObject = {"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"};
    var myJSON = JSON.stringify(myPersonalObject);
    // Store data TO Local Storage
    localStorage.setItem("storeJSON", myJSON);

    // Retrieving data FROM Local Storage
    text = localStorage.getItem("storeJSON");
    myObject = JSON.parse(text);
    document.getElementById("myData").innerHTML = myObject.firstName + " " + myObject.lastName;

    } // end of window.onload function
    </script>
  2. CHECK POINT: Save the file and preview it in a browser. You should see Cornelius Chopin displayed on the page because it was STORE LOCALLY FIRST and then RETRIEVED. Then, press CTRL+SHIFT+I  to open the Console panel. You should see the LITERALLY text string:

    {"firstName":"Cornelius","lastName":"Chopin","title":"Instructor"}

    NOTE: In a real world example, the data would be store after someone entered information into a form field and then when the page is closed and the reopened, the data will persist.

    EXCEPTIONS:

    - A date object ("today":new Date()) is not allowed in JSON. Using the stringify function() will as the name implies convert them to strings. It can be converted back to a date object later.
    - A function is not allowed in JSON using the stringify function(). It will be removed if you attempt to add one. To work about this, the function can be converted to a string BEFORE executing the JSON.stringify() function.

    You should see: {"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor", "numClasses":"function () {return 3"}

    <script>
    var myPersonalObject = {"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor", "numClasses":function () {return 3;}};
    myPersonalObject.numClasses = myPersonalObject.numClasses.toString();
    var myJSON = JSON.stringify(myPersonalObject);
    document.getElementById("myData").innerHTML = myJSON; </script>

Looping An Object

Example Page

The for..in loop is used to get the properties of an object. Since the JavaScript object can be treated as an array, it can be accessed by using the object property.

  1. Write the following HTML in the body:

    <h1 id="myData"></h1>
  2. Write the following highlighted code within a script tag and within a window.onload code block:

    <script>
    window.onload = function(){
    var myPersonalObject = {"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"};
    for (x in myPersonalObject) {
        document.getElementById("myData").innerHTML += x + "<br>";
    }

    } // end of window.onload function
    </script>
  3. CHECK POINT: Save the file and preview it in a browser. You should see the object's property names: firstName, lastName and title shown on separate lines. Not quite what we wanted. This will be resolved in the next step.

  4. Write the following code below the previous code:

    var myPersonalObject = {"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"};
    for (x in myPersonalObject) {
        document.getElementById("myData").innerHTML += x + "<br>";
    }
    var myPersonalObject = {"firstName":"Cornelius", "lastName":"Chopin", "title":"Instructor"};
    for (x in myPersonalObject) {
    document.getElementById("myData").innerHTML += myPersonalObject[x] + "<br>";
    }
  5. CHECK POINT: Save the file and preview it in a browser. You should see the object's property values: Cornelius, Chopin, and Instructor shown on separate lines.

Nesting Objects

Example Page

An object or multiple objects can be nested inside of its parent object.

  1. Write the following HTML in the body:

    <h1 id="myData"></h1>
  2. Write the following highlighted code within a script tag and within a window.onload code block:

    <script>
    window.onload = function(){
    // Nesting Objects var myWorkObject = {"firstName":"Cornelius",
    "lastName":"Chopin",
    "title":"Instructor",
    "classes": {"class1":"Photoshop",
    "class2":"Dreamweaver",
    "class3":"Illustrator"} }; document.getElementById("myData").innerHTML = myWorkObject.classes.class1;

    } // end of window.onload function
    </script>
  3. CHECK POINT: Save the file and preview it in a browser. You should see Photoshop displayed on the pageel.

    NOTE: You could have also accessed the property using the array syntax: document.getElementById("myData").innerHTML = myWorkObject.classes["class1"];

    You access or modify a nested object just like regular object, but you have to DRILL DOWN farther into the object:

    ACCESS:  var access_object = myWorkObject.classes.class1;
    MODIFY: myWorkObject.classes.class1 = "After Effects";  or myWorkObject.classes["class1"] = "After Effects";

Looping Nested Objects

You can also loop through nested objects. The key is that you have to DRILL DOWN farther into the object.

  1. Write the following HTML in the body:

    <h1 id="myData"></h1>
  2. Write the following highlighted code within a script tag and within a window.onload code block:

    <script>
    window.onload = function(){
    // Looping Nested Objects ...
    } // end of window.onload function
    </script>
  3. CHECK POINT: Save the file and preview it in a browser. You should see Photoshop displayed in the console panel.

    NOTE: You could have also accessed the property using the array syntax: document.getElementById("myData").innerHTML = myWorkObject.classes["class1"];

    You access or modify a nested object just like regular object, but you have to DRILL DOWN farther into the object:

    ACCESS:  var access_object = myWorkObject.classes.class1;
    MODIFY: myWorkObject.classes.class1 = "After Effects";  or myWorkObject.classes["class1"] = "After Effects";

Delete Object's Property

The delete keyword is used to delete an object's property (duh).

  1. Write the following highlighted code within a script tag and within a window.onload code block:

    NOTE: The "for" loop is only used to show that the object's property was indeed deleted.

    // Deleting an object's property
    <script>
    window.onload = function(){ var myWorkObject = {"firstName":"Cornelius",
    "lastName":"Chopin",
    "title":"Instructor",
    "classes": {"class1":"Photoshop",
    "class2":"Dreamweaver",
    "class3":"Illustrator"} }; document.getElementById("myData").innerHTML += myWorkObject.classes.class1;

    delete myWorkObject.class.class2; for (i in myWorkObject.classes) {
    x += myWorkObject.class[i] + "<br>";
    }
    document.getElementById("myData").innerHTML = x;
    } // end of window.onload function
    </script>
  2. CHECK POINT: Save the file and preview it in a browser. You should see that Dreamweaver is not listed in the result.

JSON From A PHP Server

Example Page

JSON is commonly used to read data from a web server to display it on a web page. PHP has built-in functions that works with PHP.  JavaScript objects can be converted into JSON using the json_encode() function.

 JSON HTML

JSON HTML content goes here...

JSONP

JSONP content goes here...

JSON vs XML

There are alot of SIMILARITIES between JSON and XML. They both:

However, there are some DIFFERENCES betweeen JSON and XML. JSON:

See examples below:

// JSON EXAMPLE
{"employees":[
    { "firstName":"Cornelius", "lastName":"Chopin" },
    { "firstName":"John", "lastName":"Doe" },
    { "firstName":"Mary", "lastName":"Jane" }
]}

NOTE: As part of a name/value pair, notice that "employees" is the name and the value is an array of objects.

// XML EXAMPLE
<employees>
    <employee>
        <firstName>Cornelius</firstName> 
<lastName>Chopin</lastName>
    </employee>
    <employee>
        <firstName>John</firstName> 
<lastName>Doe</lastName>
    </employee>
    <employee>
        <firstName>Mary</firstName> 
<lastName>Jane</lastName>
    </employee>
</employees>

NOTE: It is common practice to use a PLURAL noun (employees) as the top-level node of an XML file and a SINGLE noun (employee) as the repeating nodes.