Introduction to JSON
Introduction to JSON
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
Like XML, 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. Otherwise, inside the brackets, you can create one or more properties. A property is created as a name : value expression (the space is used here to make it easy to read). Inside the brackets, you can create as many properties as you want. The properties must be separated by commas.
The name of a property can be anything, such as an alphabetical letter, a non-readable symbol, a number, a word, or an expression. The most important rule is that the name must be included in double-quotes.
As we saw already when 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:
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:
A JSON Document as an Array of Objects
As we saw with XML, the items of a JSON file should be considered as a collection of values. For this reason, as seen in the previous section, 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 seen when studying arrays in C# and JavaScript, an array of objects is an 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:
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>
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:
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:
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:
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:
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:
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:
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:
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.
|
||
Previous | Copyright © 2018-2019, FunctionX | Next |
|