Tech Junkie Blog - Real World Tutorials, Happy Coding!: JSON (JavaScript Object Notation) : Using JSON With JavaScript

Friday, April 3, 2015

JSON (JavaScript Object Notation) : Using JSON With JavaScript

JSON is becoming the standard way to exchange data in a relatively short amount of time. The reason is because JSON is easier to work with than XML.

JSON Object:
  • JSON object is made up of name/value pairs
Single Object:

{ "firstName" : "John"}


Multiple Objects:

{ "firstName" : "John", "lastName" : "Doe"}

  •  JSON array has the following syntax [{object}], in the following example "asset" is a JSON array
{
    "firstName": "John",
    "lastName": "Doe",
    "asset": [
        {
            "assetType": "Stock",
            "assetName": "FB"
        },
        {
            "assetType": "Building",
            "assetName": "Condo"
        }
    ]
}
  • JSON values can be the following types:
    • String
    • Numeric
    • Object
    • Array
    • Boolean
    • null
Example of JSON with different types:

{
    "firstName": "John",
    "lastName": "Doe",
    "asset": [
        {
            "assetType": "Stock",
            "assetName": "FB"
        },
        {
            "assetType": "Building",
            "assetName": "Condo"
        }
    ],
    "isClient": true,
    "age": 45,
    "dob": "03/25/1970",
    "race": null
}

  • Using JSON in JavaScript
  
var johnRecord = {
    "firstName": "John",
    "lastName": "Doe",
    "asset": [
        {
            "assetType": "Stock",
            "assetName": "FB"
        },
        {
            "assetType": "Building",
            "assetName": "Condo"
        }
    ],
    "isClient": true,
    "age": 45,
    "dob": "03/25/1970",
    "race": null
}


Save the above code as a .js file and call it johnRecord.js
Now create an html file with the following markup

<!DOCTYPE html>
<html lang="en">
<head>
<title>JSON Demo</title>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="johnRecord.js"></script>
<script>
     $(function(){
  var existingClient = johnRecord.isClient ? "Yes" : "No";
  
  $("p#json-record").html("<b>First Name</b>: " + johnRecord.firstName + "<br>" + "<b>Last Name</b>: " + johnRecord.lastName + 
    "<br/><b>Existing Client</b>: " + existingClient + "<br/><b>Race:</b> " + johnRecord.race +
    "<br/><b>Date Of Birth:</b> " + johnRecord.dob + "<br/><b>Age:</b> " + johnRecord.age);
    $.each(johnRecord.asset, function(key,value) {
   $("p#assets").append("<br/><b>Type:</b> " + value.assetType + " <b>Assets:</b> " + value.assetName);
    });
  });
</script>
</head>
<body>
<p id="json-record"/>
<p id="assets"/>
</body>
</html>

Explaination:

<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="johnRecord.js"></script>
<script>
     $(function(){
  var existingClient = johnRecord.isClient ? "Yes" : "No";
  
  $("p#json-record").html("<b>First Name</b>: " + johnRecord.firstName + "<br>" + "<b>Last Name</b>: " + johnRecord.lastName + 
    "<br/><b>Existing Client</b>: " + existingClient + "<br/><b>Race:</b> " + johnRecord.race +
    "<br/><b>Date Of Birth:</b> " + johnRecord.dob + "<br/><b>Age:</b> " + johnRecord.age);
    $.each(johnRecord.asset, function(key,value) {
   $("p#assets").append("<br/><b>Type:</b> " + value.assetType + " <b>Assets:</b> " + value.assetName);
    });
  });
</script>

Let's concentrate on the JavaScript part of the code, which retrieves and displays the JSON data in the <p id="john-record"> and the <p id="assets"> tags.
First we save the JSON data in a JavaScript file with the extension .js.  Then we use JQuery to display the JSON data in the paragraph tag with the id "json-record" and "assets".  We access the JSON fields just like any other JavaScript object's field with the dot . notation.  So to access the firstName field of the JSON data in our HTML page we type the following johnRecord.firstName.  Another thing I want to point out is that in our .js file we use the boolean type true or false for the isClient field.  Well in our JQuery function we can treat the field like any other JavaScript boolean variable.  With the code

var existingClient = johnRecord.isClient ? "Yes" : "No";

We use ternary operators to specify whether we want to display "Yes" or "No", and then we display the response accordingly when we populate the paragraph tag with the id "john-record", so instead of true or false, we display "Yes" or "No" instead.

As for the array "asset" we use the JQuery $.each function to loop through the array with function(key,value), the key is the name of the field, and the value is the value of the field. We could use regular JavaScript to work with JSON data, but it's so much easier to use JQuery. JQuery is so smooth it's like butter. To me, it's the best thing that happened to JavaScript. JavaScript is like the mad scientist, while JQuery is like the cool kid who sales the JavaScript. Kinda like Steve & The Woz. Here is the result when you view it in a browser:
























Previous: JavaScript: Arrays
Next: JavaScript: undefined vs null

1 comment:

Search This Blog