The JavaScript Object Notation

Introduction

The JavaScript Object Notation, or JSON, is a meta-language used to create sections of text in a format that can be easily read, analyzed, and interpreted. This puts JSON in the categories of meta-languages like XML. JSON follows the ways arrays of objects are created in JavaScript. This means that, if/since you (already) know how arrays of objects are created in JavaScript, JSON will be particularly easy for you. This also means that you don't need to learn a new language: you will simply apply your knowledge of JavaScript object construction and arrays into JSON.

A JSON File

JSON is created as a text-based document. After starting or creating the document, save it with the .json extension. In Microsoft Visual Studio, to add a JSON file to a project, in the Solution Explorer, right-click either the name of the project or the folder that will host the file, position the mouse on Add, and click New Item... In the left frame of the Add New Item dialog box, click Web and click Markup. In the middle frame, click JSON file. Accept the suggested name of the file or change it. When you are ready, click OK.

Introduction to the Structure of a JSON Document

A JSON document is made of one or more JavaScript objects. Remember that, in JavaScript, the body of an object starts with an opening curly bracket { and ends with a closing curly bracket }. To have an empty or null object, you can leave the curly brackets empty. Here is an example:

{}

Of course, you can write the closing curly bracket on its own line. Inside the brackets, you can create one or more properties. A property is created as a name : value expression (the optional space is used here to make it easy to read). Inside the brackets, you can create one or as many properties as you want. The properties must be separated by commas.

The name of a property can be anything, such as a letter, a non-readable symbol, a number, a word, or an expression (a combination of letters, words, digits, symbols, etc). The most important rule is that the name must be included in double-quotes.

As you should know already from studying JavaScript, a value can be a string, in which case it would be included in double-quotes. Here is an example:

{
    "toyName": "Mini Point of Sale Station"
}

In the same way, you can create as many properties as you want in the object.

Opening a JSON File

As mentioned already, a JSON file is just a text-based document. You can use any text editor to open it. To programmatically open a JSON file, you can use an XMLHttpRequest object. Specify the name or address of the file as the second argument of the XMLHttpRequest.open() method. In this case, the method would produce the whole document as one string. The string includes every symbol and letter from beginning to end. Here is an example:

JSON File: Toys.json

{
  "M":"Mini Point of Sale Station",
  "@":"Drawing Black Board",
  "2":"Kid Ferry Boat",
  "true":"Easter Egg Decorating Set"
}

HTML File: Inventory.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Children Toys Store</title>
</head>
<body>
<script type="text/javascript">
    (function showMessage() {
        var xhrService = new XMLHttpRequest();

        xhrService.onreadystatechange = function () {
            if (xhrService.readyState == XMLHttpRequest.DONE && xhrService.status == 200) {
                var toys = xhrService.responseText;
                document.write(toys);
            }
        };
        xhrService.open("GET", "Toys.json", true);
        xhrService.send();
    })();
</script>
</body>
</html>

This would produce:

Opening a JSON File

A JSON Object

To give you programmatic access to the contents of a JSON document, the JavaScript language provides an object named JSON. It is equipped with just a few but valuable members.

Characteristics of a JSON Document

The Value as a Number

The value of a property of a JSON object can be a number. Here is an example:

{ "itemNumber": 937495 }

A Boolean Value

The value of a property can be Boolean as true or false. Here is an example:

{
    "itemNumber": 749374,
    "toyName": "Kid Ferry Boat",
    "unitPrice": 24.86,
    "needsParentalSupervision" : true
}

The Value as an Object

The value of a property can be an object. Here are examples:

{
    "accountNumber": "792-030-973",
    "customerName": {
        "firstName": "Doris",
        "MI": "P",
        "lastName": "Papadopoulos"
    },
    "address": {
        "location": "3748 Earstern Ave",
        "city": "Lancaster",
        "state": "PA"
    },
    "category": "Residential",
    "contact": {
        "emailAddress": "dpapa@mailcity.com",
        "phoneNumber": "103-084-9741",
        "socialPage": "My Space: Papadopoulos Business"
    }
}

A Null Value

If you don't have a value for a property, you can set it as null.

JSON and Arrays

Introduction

An array is an item that starts with an opening square bracket [ and ends with a closing square bracket ]. Here is an example:

[]

This is referred to as an empty array. Normally, to make it useful, an array should contain one or more values. Here is an example:

JSON File: Toys.json

[ "Mini Point of Sale Station",
  "Drawing Black Board",
  "Kid Ferry Boat",
  "Easter Egg Decorating Set" ]

The code to open the file is the same we used earlier. It would produce:

Opening a JSON File

A JSON Document as an Array of Objects

The items of a JSON file should be considered a collection of values. For this reason, you should put them in an array. Of course, a collection of strings as seen above is too simple and one-dimensional. If you want each item to hold more information, you should create the collection as an array of objects.

As you may know from studying arrays in C# and JavaScript, an array of objects is a collection that contains objects. To get such an array in your JSON document, you can create an object in square brackets. Here is an example:

JSON File: Toys.json

[{
    "itemNumber": 937495,
    "toyName": "Mini Point of Sale Station",
    "unitPrice": 32.64
}]

The file is accessed as done previously. It would produce:

Opening a JSON File

In your JSON document, you can create as many objects as you want inside the square bracckets of the array. The objects must be separated with commas. Here is an example:

[
  {
    "itemNumber": 937495,
    "toyName": "Mini Point of Sale Station",
    "unitPrice": 32.64
  },
  {
    "itemNumber": 309581,
    "toyName": "Drawing Black Board",
    "unitPrice": 18.45
  },
  {
    "itemNumber": 749374,
    "toyName": "Kid Ferry Boat",
    "unitPrice": 24.86
  },
  {
    "itemNumber": 583049,
    "toyName": "Easter Egg Decorating Set",
    "unitPrice": 32.04
  }
]

The file is accessed as done previously. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Children Toys Store</title>
</head>
<body>
<script type="text/javascript">
    (function showMessage() {
        var xhrService = new XMLHttpRequest();

        xhrService.onreadystatechange = function () {
            if (xhrService.readyState == XMLHttpRequest.DONE && xhrService.status == 200) {
                
            }
        };
        xhrService.open("GET", "Toys.json", true);
        xhrService.send();
    })();
</script>
</body>
</html>

Opening a JSON File

Parsing a JSON Document

To give you access to each member of the array of objects of a Json document, the JSON object is equipped with a method named parse. Its syntax is:

parse(text[, reviver])

This method takes a required and an optional arguments. The required argument is the text that must be parsed. It can be the responseText property of an XMLHttpRequest object. Here is an example of calling the method:

JSON File: Toys.json

[
  "Mini Point of Sale Station",
  "Drawing Black Board",
  "Kid Ferry Boat",
  "Easter Egg Decorating Set"
]

HTML File: Inventory.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Children Toys Store</title>
</head>
<body>
<script type="text/javascript">
    (function showMessage() {
        var xhrService = new XMLHttpRequest();

        xhrService.onreadystatechange = function () {
            if (xhrService.readyState == XMLHttpRequest.DONE && xhrService.status == 200) {
                var toys = JSON.parse(xhrService.responseText);
                document.write(toys);
            }
        };
        xhrService.open("GET", "Toys.json", true);
        xhrService.send();
    })();
</script>
</body>
</html>

This would produce:

Opening a JSON File

The JSON.parse() method returns the collection of items in a JSON file as an array of objects. As a result, your can access each item by its index. The first item in the array is at index 0, the second at index 1, and so on. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Children Toys Store</title>
</head>
<body>
<script type="text/javascript">
    (function showMessage() {
        var xhrService = new XMLHttpRequest();

        xhrService.onreadystatechange = function () {
            if (xhrService.readyState == XMLHttpRequest.DONE && xhrService.status == 200) {
                var toys = JSON.parse(xhrService.responseText);
                document.write(toys[1]);
            }
        };
        xhrService.open("GET", "Toys.json", true);
        xhrService.send();
    })();
</script>
</body>
</html>

This would produce:

Opening a JSON File

Of course, you can use a loop to get to each item. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Children Toys Store</title>
</head>
<body>
<script type="text/javascript">
    (function showMessage() {
        var xhrService = new XMLHttpRequest();

        xhrService.onreadystatechange = function () {
            if (xhrService.readyState == XMLHttpRequest.DONE && xhrService.status == 200) {
                var toys = JSON.parse(xhrService.responseText);

                document.write("<ul>");
                for (var toy in toys)
                    document.write("<li>" + toys[toy] + "</li>");
                document.write("</ul>");
            }
        };
        xhrService.open("GET", "Toys.json", true);
        xhrService.send();
    })();
</script>
</body>
</html>

thiswould produce:

Opening a JSON File

In the same way, if your JSON document contains an array of objects, you can access each object by its index. This would be done as follows:

var toys = JSON.parse(xhrService.responseText);

toys[1]

Once you have accessed an object by its index, to access a property, type a period and the name of the desired property. Here is an example:

JSON File: Toys.json

[
  {
    "itemNumber": 937495,
    "toyName": "Mini Point of Sale Station",
    "unitPrice": 32.64
  },
  {
    "itemNumber": 309581,
    "toyName": "Drawing Black Board",
    "unitPrice": 18.45
  },
  {
    "itemNumber": 749374,
    "toyName": "Kid Ferry Boat",
    "unitPrice": 24.86
  },
  {
    "itemNumber": 583049,
    "toyName": "Easter Egg Decorating Set",
    "unitPrice": 32.04
  }
]

HTML File: Inventory.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Children Toys Store</title>
</head>
<body>
<script type="text/javascript">
    (function showMessage() {
        var xhrService = new XMLHttpRequest();

        xhrService.onreadystatechange = function () {
            if (xhrService.readyState == XMLHttpRequest.DONE && xhrService.status == 200) {
                var toys = JSON.parse(xhrService.responseText);

                document.write("<h1>Children Toy Store</h1>");

                document.write("<b>Item #:</b>" + toys[1].itemNumber + "<br>");
                document.write("<b>Toy Name:</b>" + toys[1].toyName + "<br>");
                document.write("<b>Price:</b>" + toys[1].unitPrice);
            }
        };
        xhrService.open("GET", "Toys.json", true);
        xhrService.send();
    })();
    </script>
</body>
</html>

This would produce:

Parsing a JSON Document

In the same way, you can use a loop to access each object and its properties. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Children Toys Store</title>
</head>
<body>
<script type="text/javascript">
    (function showMessage() {
        var xhrService = new XMLHttpRequest();

        xhrService.onreadystatechange = function () {
            if (xhrService.readyState == XMLHttpRequest.DONE && xhrService.status == 200) {
                var toys = JSON.parse(xhrService.responseText);

                document.write("<h1>Children Toy Store</h1>");

                document.write("<table border='5'>")
                document.write("<tr><td><b>Item #</b></td><td><b>Toy Name</b></td><td><b>Price</b></td></tr>");

                for (var toy in toys) {
                    document.write("<tr><td>" + toys[toy].itemNumber + "</td>");
                    document.write("<td>" + toys[toy].toyName + "</td>");
                    document.write("<td>" + toys[toy].unitPrice + "</td></tr>");
                }
                document.write("</tr>");
            }
        };
        xhrService.open("GET", "Toys2.json", true);
        xhrService.send();
    })();
    </script>
</body>
</html>

thiswould produce:

Opening a JSON File

A JSON Value as an Array

The value of a property of a JSON item can be an array. Here are examples:

[
  {
    "employeeNumber": 927049,
    "fullName": [ "James", "H", "Daniels" ],
    "hourlySalary": 21.86,
    "filingStatus": [ "Married", 3 ],
    "children": [
        {
            "name": "Reobert Sanford",
            "age": 8
        },
        {
            "name": "Annette Binam",
            "age": 10
        },
        {
            "name": "Lydia Major",
            "age":  12
        }
    ]
  }
]

An Object for a Property

We saw that the value of a property could be an object. Here is an example of a JSON document that contains one object in an array:

JSON File: Customers.json

[{
    "accountNumber": "792-030-973",
    "customerName": {
        "firstName": "Doris",
        "MI": "P",
        "lastName": "Papadopoulos"
    },
    "address": {
        "location": "3748 Earstern Ave",
        "city": "Lancaster",
        "state": "PA"
    },
    "category": "Residential",
    "contact": {
        "emailAddress": "dpapa@mailcity.com",
        "phoneNumber": "103-084-9741",
        "socialPage": "My Space: Papadopoulos Business"
    }
}]

Once again, each object can be accessed by its index. From that index, you can access the name of a property, such as customerName in this example. From there, you can access a property of the nested object. Here are examples:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Customer Record</title>
</head>
<body>
    <script type="text/javascript">
        (function showMessage() {
            var xhrService = new XMLHttpRequest();

            xhrService.onreadystatechange = function () {
                if (xhrService.readyState == XMLHttpRequest.DONE && xhrService.status == 200) {
                    var customers = JSON.parse(xhrService.responseText);

                    document.write("<h1>Customer Record</h1>");

                    document.write("<table border='1'>");
                    document.write("<tr><td><b>Account #:</b></td><td>" + customers[0].accountNumber + "</td></tr>");
                    document.write("<tr><td><b>Customer Name:</b></td><td>" +
                        customers[0].customerName.firstName + " " +
                        customers[0].customerName.MI + " " +
                        customers[0].customerName.lastName + "</td></tr>");
                    document.write("<tr><td><b>Address:</b></td><td>" + customers[0].address.location + " " +
                        customers[0].address.city + " " +
                        customers[0].address.state + "</td></tr>");
                    document.write("<tr><td><b>Category:</b></td><td>" + customers[0].category + "</td></tr></table>");
                }
            };
            xhrService.open("GET", "Customers.json", true);
            xhrService.send();
        })();
    </script>
</body>
</html>

this would produce:

Opening a JSON File

As mentioned previously, the value of a property of an object can be an array. Here are example:

JSON File: RepairOrders.json

[
  {
    "repairNumber": 100001,
    "car": { "make": "Toyota", "model": "Corolla", "year": 2010 },
    "partsUsed": [
        {
            "partName": "Air Filter",
            "price": 8.95
        },
        {
            "partName": "Gasket Intake Manifold",
            "price": 225.67
        },
        {
            "partName": "Front Wheel Hub Bearing Kit",
            "price": 96.88
        },
        {
            "partName": "Oil Seal",
            "price": 6.34
        }],
    "jobsPerformed": [
        {
            "jobName": "Performed complete tune-up",
            "price": 54.85
        },
        {
            "jobName": "Balanced the tires",
            "price": 19.95
        }]
    }
]

To access an object in a nested array, first access the parent property from its index. Everything else is done as when accessing an array, a nested object, or a nested array. Here are examples:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>CPAR - Repair Order</title>
</head>
<body>
<script type="text/javascript">
    (function showMessage() {
        var xhrService = new XMLHttpRequest();

        xhrService.onreadystatechange = function () {
            if (xhrService.readyState == XMLHttpRequest.DONE && xhrService.status == 200) {
                var repairs = JSON.parse(xhrService.responseText);

                document.write("<h1>College Park Auto Repair</h1>");
                document.write("<h2>Repair Order</h1>");

                document.write("<p><b>Repair #:</b>" + repairs[0].repairNumber + "</p>");
                document.write("<p><b>Car:</b> " + repairs[0].car.make + " " + repairs[0].car.model + " " + repairs[0].car.year + "</p>");

                document.write("<h3><b>Parts Used</b></h3>");

                document.write("<table border='2'>");
                document.write("<tr><td><b>Parts Name</b></td><td><b>Price</b></td></tr>");
                document.write("<tr><td>" + repairs[0].partsUsed[0].partName + "</td><td>" + repairs[0].partsUsed[0].price + "</td></tr>");
                document.write("<tr><td>" + repairs[0].partsUsed[1].partName + "</td><td>" + repairs[0].partsUsed[1].price + "</td></tr>");
                document.write("<tr><td>" + repairs[0].partsUsed[2].partName + "</td><td>" + repairs[0].partsUsed[2].price + "</td></tr>");
                document.write("<tr><td>" + repairs[0].partsUsed[3].partName + "</td><td>" + repairs[0].partsUsed[3].price + "</td></tr></table>");

                document.write("<h3><b>Jobs Performed</b></h3>");

                document.write("<table border='2'>");
                document.write("<tr><td><b>Job Name</b></td><td><b>Price</b></td></tr>");
                document.write("<tr><td>" + repairs[0].jobsPerformed[0].jobName + "</td><td>" + repairs[0].jobsPerformed[0].price + "</td></tr>");
                document.write("<tr><td>" + repairs[0].jobsPerformed[1].jobName + "</td><td>" + repairs[0].jobsPerformed[1].price + "</td></tr></table>");
            }
        };
        xhrService.open("GET", "RepairOrders.json", true);
        xhrService.send();
    })();
    </script>
</body>
</html>

thiswould produce:

Opening a JSON File

Converting an Object to String for AJAX

A value you want to send to a webserver should be sent as a string recognized by JSON. To let you convert the value to such a string, the JSON object is equipped with a method named stringify. Its syntax is:

stringify(value, replacer = object, space = string or number);

This method takes one required and two optional arguments. The required argument, value, is the expression to convert to a valid JSON string. The optional replacer argument describes how the conversion should be made in case you prefer it to be done a certain way. The optional space argument specifies an empty string to be included in the resulting string, or the number of empty spaces to be included in the result.

Introduction to JSON in jQuery

Overview

Consider a Json file named WaterMeters created in a folder named WaterDistributions as follows:

[
  {
    "meterNumber": "293-740",
    "make": "Breston",
    "model": "S-93749",
    "meterSize": "3/4 Inches"
  },
  {
    "meterNumber": "820-418",
    "make": "Vashty Worldwide",
    "model": "DD-3840",
    "meterSize": "3/4 Inches"
  },
  {
    "meterNumber": "627-425",
    "make": "Breston",
    "model": "T-39478",
    "meterSize": "5/8 Inches"
  },
  {
    "meterNumber": "304-861",
    "make": "Vashty Worldwide",
    "model": "DD-3840",
    "meterSize": "3/4 Inches"
  },
  {
    "meterNumber": "925-935",
    "make": "Igawa International",
    "model": "DTT 8802",
    "meterSize": "1 Inch"
  },
  {
    "meterNumber": "779-958",
    "make": "Igawa International",
    "model": "DMG 4000",
    "meterSize" : "3/4 Inches"
  }
]

We saw that, to open and read an Ajax file, the jQuery object is equipped with a method named ajax. That method takes two arguments. The first argument is an object that idenfies the Json file to be opened. When using a Json file, you can specify the value of the dataType property as "json". This could be done as follows:

$.ajax({
    url: "/WaterDistribution/WaterMeters.json",
    method: "GET",
    dataType: "json",
    success: . . .
});

To process the data, add a success property. The value of this property is a function that will process the case of a successful outcome. In the function that processes the successful outcome of reading the data, you can first pass a data object as argument. In the body of the function argument, you can call an $.each() method to visit each record of the Json file.

Remember that the $.each() method takes two arguments. The first argument is the same data object that was passed to the $.each() method. The second argument is a function that the $.each() method processes. In that method, access each record of the Json file and use it as you see fit. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Water Distribution Company</title>
<script src="Scripts/jquery-1.10.2.js"></script>
<link href="Content/bootstrap.css" rel="stylesheet" />
</head>
<body>
<h1 class="text-center">Water Distribution Company</h1>
<h2 class="text-center">Water Meters</h2>

<table class="table table-striped">
        <tr>
            <td style="font-weight: 600">Meter #</td>
            <td style="font-weight: 600">Make</td>
            <td style="font-weight: 600">Model</td>
            <td style="font-weight: 600">Meter Size</td>
        </tr>
    </table>

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            url: "/WaterDistribution/WaterMeters.json",
            method: "GET",
            dataType: "json",
            success: function (data) {
                $.each(data, function (index, waterMeter) {
                    $("table").append("<tr><td>" + waterMeter["meterNumber"] +
                                     "</td><td>" + waterMeter["make"] +
                                     "</td><td>" + waterMeter["model"] +
                                     "</td><td>" + waterMeter["meterSize"] + "</td></tr>");
                });
            }
        });
    });
</script>
</body>
</html>

This would produce:

Introduction to JSON in jQuery

In the body of the jQuery.getJSON() method, if you are plaaning to use the result of processing the Json data many times, you can first store it in a local array variable. Here is an example:

$.ajax({
    url: "/WaterDistribution/WaterMeters.json",
    method: "GET",
    dataType: "json",
    success: function (data) {
        var waterMeters = [];

        $.each(data, function (index, waterMeter) {
            waterMeters.push("<tr><td>" + waterMeter["meterNumber"] +
                            "</td><td>" + waterMeter["make"] +
                            "</td><td>" + waterMeter["model"] +
                            "</td><td>" + waterMeter["meterSize"] + "</td></tr>");
        }); // Each Water Meter

        $("table").append(waterMeters);
    } // Success
}); // Ajax     

Getting a JSON File

Consider the following file named Customers.json and created in the WaterDistribution folder:

[
  {
    "accountNumber": "7029-371-8594", "meterNumber": "293-740",
    "firstName": "Danielle", "lastName": "Dormand",
    "address": "2515 Guthierez Street",
    "city": "Falls Church", "county": "",
    "state": "VA", "zipCode": "22046"
  }, {
    "accountNumber": "1848-205-3313", "meterNumber" : "925-935",
    "firstName" : "Frank", "lastName" : "Nounkeu",
    "address": "13931 Wellington Street",
    "city": "College Park", "county": "Prince George",
    "state": "MD", "zipCode": "20740"
  }, {
    "accountNumber": "4024-850-0482", "meterNumber": "820-418",
    "firstName": "Marianne", "lastName": "Pettersen",
    "address": "10572 Maya Blvd",
    "city": "Frederick", "county": "Frederick</county>",
    "state": "MD", "zipCode": "20111"
  }, {
    "accountNumber" : "8046-728-5060", "meterNumber" : "304-861",
    "firstName" : "Augustino", "lastName" : "Derbez",
    "address" : "7507 Westchester Ave", "city" : "Washington",
    "county": "", "state": "DC", "zipCode": "20008"
  },{
    "accountNumber" : "2958-314-5294", "meterNumber" : "627-425",
    "firstName" : "Nicholas", "lastName" : "Thorn",
    "address": "2599 Phenicia Road",
    "city" : "Silver Spring", "county": "Montgomery",
    "state": "MD", "zipCode": "20906"
  }
]

The $.ajax() method is used for various types of Ajax operations, reading (that is, getting) data is only one of them, in which case you should set a "GET" value to its METHOD property. To provide a shortcut to this approach, the jQuery object is equipped with a method named getJSON. Its syntax is:

jQuery.getJSON(url [, data ][, success);

The jQuery.getJSON() method takes one required and two optinal arguments. The required argument is the file or the path to the Json file you want to process. The second argument is the data that will be processed. If the first argument holds the data, you can omit this argument. The third argument is the function that will process the successful outcome of processing the data. This function taks an argument that holds the data to be processed.

Once again, in the body of the function, you can call the $.each() method to visit each record if the Json file. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Water Distribution Company - Customers</title>
<script src="Scripts/jquery-1.10.2.js"></script>
<link href="Content/bootstrap.css" rel="stylesheet" />
</head>
<body>
<h1 class="text-center">Water Distribution Company</h1>
<h2 class="text-center">Customers</h2>

<table border="3" class="table table-hover">
    <tr>
        <td style="font-weight: 600">Account #</td>
        <td style="font-weight: 600">Meter #</td>
        <td style="font-weight: 600">First Name</td>
        <td style="font-weight: 600">Last Name</td>
        <td style="font-weight: 600">Address</td>
        <td style="font-weight: 600">City</td>
        <td style="font-weight: 600">County</td>
        <td style="font-weight: 600">State</td>
        <td style="font-weight: 600">ZIP-Code</td>
    </tr>
</table>

<script type="text/javascript">
    $(document).ready(function () {
        $.getJSON("/WaterDistribution/Customers.json",
            function (data) {
                $.each(data, function (index, customer) {
                    $("table").append("<tr><td>" + customer["accountNumber"] + "</td><td>" +
                        customer["meterNumber"] + "</td><td>" +
                        customer["firstName"] + "</td><td>" +
                        customer["lastName"] + "</td><td>" +
                        customer["address"] + "</td><td>" +
                        customer["city"] + "</td><td>" +
                        customer["county"] + "</td><td>" +
                        customer["state"] + "</td><td>" +
                        customer["zipCode"] + "</td></tr>");
                });
            });
      });
    </script>
</body>
</html>

This would produce:

String Comparison

Once again, if you want to use the Json data more than once, you can store it in a local array variable.

Promising an Ajax Outcome

As seen in our introduction to Ajax, jQuery supports JSon on the concept of promises. If using promises, the jQuery.getJSON() method may use the following formula:

$.getJSON(url, function() {
	. . .
}).done(function() {
	. . .
}).fail(function() {
	. . .
}).always(function() {
	. . .
});

The done() method is used to process the successful outcome. The fail() is used in case there is an error or there are errors. Add an always() method for code you want to execute regardless of the outcome.


Previous Copyright © 2017-2019, FunctionX Next