Section 1: Introduction

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.
from Introducing JSON
JSON is a data format much like XML or CSV, just with a different set of formatting rules.
JSON is nothing more (and nothing less) than a format of the data you transfer with the Ajax-way of talking to the server.
JSON is not a competing technology to AJAX, it's just a data format.
Where you might hear competition is between XML and JSON, JSON having the advantage of being typically lighter and in native JavaScript already, XML having the advantage of portability and toolsets. Some transfer the data in the form of XML, others just plain text, others use JSON.
from When to use Ajax vs Json for Javascript events?
You can find interesting comparisons at Difference between Ajax and JSON and Difference Between JSON and AJAX.





Section 2: JSON Purposes & Advantages
- Used to pass data.
- Lightweight format that is used for data interchanging.
- Easy for humans to read and write.
- Easy for machines to parse and generate.
- Based on a subset of JavaScript (follows JavaScript object syntax).
- Text format that is completely language independent.
- Supported by most modern programming languages.
- Good overview video: JSON Crash Course
JSON Requirements
The JSON is built on two structures:
-
A collection of name/value pairs.
- In many programming languages, we often refer to this as an object, record, struct, dictionary, hash table, etc.
-
An ordered list of values.
- In many programming languages, we refer to this as an array, vector, list, or sequence.
An example can be viewed in What is JSON (JavaScript Object Notation)?.
Section 3: JSON Syntax and Examples
JSON Object
- Based off object literals in JavaScript
- Unordered list of name:value pairs
- Starts with
{
(left-brace) - Ends with
}
(right-brace) - Name followed by
:
(colon) -
Name-Value Pairs separated by
,
(comma)
Values can be
-
String
- JSON requires double quotes for its strings. Not single quotes.
- JSON text SHALL be encoded in Unicode. The default encoding is UTF-8.
- Number
-
Object
- Defined with { : , } format
- Defined with { : , } format
-
Array
- Defined with [ , ] format
- Defined with [ , ] format
- Boolean
- Null
Examples

Here is an example of JSON, implemented as an array of objects.
// This is an example of JSON - an array of objects. JSON is a popular and
// agreed-upon format for sending, receiving, and storing data.
var ourCourses = [
{
"courseNum": "INFO1181",
"courseName": "Programming I",
"courseLanguage": "Python"
},
{
"courseNum": "INFO2220",
"courseName": "Front-end Development",
"courseLanguage": "JavaScript"
},
{
"courseNum": "INFO4407",
"courseName": "Database Design",
"courseLanguage": "SQL"
}
]
You can view additional examples at JSON Example and 10 JSON Examples to Use in Your Projects.
Quotes around names
You should use quotes around names:
- Based on the standard
- More semantically correct
-
Although it will be tolerated if you omit the quotes, you should use this approach:
Section 4: JSON Conversion
Convert from objects to JSON
var pers = { "name": "Bob", "age": 34 };
// convert object to JSON string.
var pJson = JSON.stringify(pers);
Convert from JSON to object
var jString = '{ "name": "Susan", "age": 32 }';
// convert JSON string to object.
var obj = JSON.parse(jString);
To to access data
Data in JSON files is just text, so it can be
-
Text file
- Normally has a json extension, but does not have to
-
Response parameter
- Technically a file is also a server response
Section 5: JSON Demos with JavaScript
I recommend that you go through the JSON and AJAX Tutorial: With Real Examples video overview, and implement the example. It will help make the overall discussion more understandable.
- You may want to use software such as Capture2Text OCR (Optical Character Recognition) functionality to copy text from the screen to the clipboard to copy the code from the screen to save typing.
- The code from the video example has been implemented in this demo, but you will learn more if you build it yourself.
Examples
JSON files can be accessed using JavaScript, or using jQuery.
- The following examples use specific approaches, but there are multiple approaches for accessing JSON files.
Accessing a JSON file using JavaScript
There are many techniques by which a JSON file can be accessed by JavaScript. The following example uses the Fetch API.
- The Fetch API interface allows web browser to make HTTP requests to web servers without using the XMLHttpRequest.
-
JSON/JavaScript example
The jquery code for the example follows:
let url = 'courseLanguages.json';
// disable CORS because path does not contain http(s)
fetch(url, { mode: "no-cors" })
// the .json() method parses the JSON response into a JS object literal
.then((response) => response.json())
.then((json) => {
var str = JSON.stringify(json, null, ' ');
ourCourses = json;
alert("The language used in " + ourCourses[0].courseNum +
" is " + ourCourses[0].courseLanguage + ".");
alert("The language used in " + ourCourses[1].courseNum +
" is " + ourCourses[1].courseLanguage + ".");
alert("The language used in " + ourCourses[2].courseNum +
" is " + ourCourses[2].courseLanguage + ".");
});The json file appears below:
[
{
"courseNum": "INFO1181",
"courseName": "Programming I",
"courseLanguage": "Python"
},
{
"courseNum": "INFO2220",
"courseName": "Front-end Development",
"courseLanguage": "JavaScript"
},
{
"courseNum": "INFO4407",
"courseName": "Database Design",
"courseLanguage": "SQL"
}
[
The following links provide additional documentation on Fetch.
Section 6: Accessing a JSON file using jQuery – $.getJSON()
As with using JavaScript, there are various techniques for accessing a JSON file using jQuery.
The following example uses jQuery's getJSON()
method.
- jQuery's getJSON() method fetches JSON-encoded data from the server using a GET HTTP request.
-
JSON/jQuery Example with
jQuery.getJSON()
The jquery code for the example follows:
$(document).ready(function() {
('button#btn').click(function() {
// Retrieving data from a JSON file
$.getJSON("courseLanguages.json",
function (data) {
// data dump
var courseNum = 1;
// get info for one course at a time
$.each(data, function(index, item) {
// get info for one course attribute (string value) at a time using
// the generic key parameter to get the associated value
$.each(item, function(key, value) {
alert('Data Dump: course#' + courseNum + '\n' + key + ': ' + value);
});
courseNum++;
});
var course = "";
// Iterating through objects using the specific key names (courseNum,
// courseLanguage) to get the associated value
$.each(data, function (index, item) {
course += "The language used in " + value.courseNum + " is ";
course += value.courseLanguage + ".";
alert(course);
course="";
});
});
});
});The json file appears below:
[
{
"courseNum": "INFO1181",
"courseName": "Programming I",
"courseLanguage": "Python"
},
{
"courseNum": "INFO2220",
"courseName": "Front-end Development",
"courseLanguage": "JavaScript"
},
{
"courseNum": "INFO4407",
"courseName": "Database Design",
"courseLanguage": "SQL"
}
[
Section 7: Accessing a JSON file using jQuery – $.ajax()
You can also use an approach similar to that used in the Ajax
discussion, that is, using the jQuery.ajax()
method.
$.ajax({
type: 'GET',
url: 'courseLanguages.json',
dataType: 'json',
success: function(data) {
var _class = "";
$.each(data, function(index, item)
{
_class += "The language used in " + item.courseNum + " is ";
_class += item.courseLanguage + ".";
alert(_class);
_class="";
});
},
error: function(xhr, status, error) {
alert("Error: " + xhr.responseText); // error occurred
}
});
Note that both approaches use jQuery’s each() function to loop through each element of the target jQuery object — an object that contains one or more DOM elements.
- The function is very useful for multi-element DOM manipulation, as well as iterating over arbitrary arrays and object properties.
Section 8: JSON in jQuery
Here is the 4430 professor's PowerPoint presentation on additional JSON concepts:
This material is also included below
There are two ways to use Ajax in jQuery.
.ajax can be used as a method or as an object.

Using the .ajax() method in jQuery
The page jQuery ajax() Method explains the following:
-
The .ajax() method is used to perform an Ajax (asynchronous HTTP) request.
$.ajax({name:value, name:value, ... })
-
The parameters each specify one or more name/value pairs for the AJAX request.
- url – Specifies the URL to send the request to. Default is the current page
- data – Specifies data to be sent to the server
- beforeSend(xhr) – A function to run before the request is sent
- success(result,status,xhr) – A function to be run when the request succeeds
- error(xhr,status,error) – A function to run if the request fails.
- complete(xhr,status) – A function to run when the request is finished (after success and error functions)

More details about each of the settings can be found in jQuery.ajax().
Using the .ajax() object in jQuery
The Promise Pattern is an approach where we set the stage for something
that will happen in the future. The promise is not that your request will be successful.
Rather, the promise is that regardless of what happens, an object will be returned. That
object has handlers for cases such as success and failure. The key is that regardless of
what happens, your calling code will get something back. From there, your code can act
accordingly. If the call is successful, your code will proceed as planned. On the other hand,
if an error occurs, your code can log the error and redirect to a user-friendly error page
or give the user a chance to re-initiate the request.
From The
Simplest Thing Possible: Promises in JavaScript.
The jqXHR objects returned by $.ajax()
as of jQuery 1.5 implement the Promise
interface, giving them all the properties, methods, and behavior of a Promise. Available Promise methods of the jqXHR object include:
-
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, refer to
deferred.done()
for implementation details. -
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
An alternative construct to the error callback option, the
.fail()
method replaces the deprecated.error()
method. Refer todeferred.fail()
for implementation details. -
jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { }); (added in jQuery 1.6)
An alternative construct to the complete callback option, the
.always()
method replaces the deprecated.complete()
method.In response to a successful request, the function's arguments are the same as those of
.done()
: data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of.fail()
: the jqXHR object, textStatus, and errorThrown. Refer todeferred.always()
for implementation details.
See jQuery.ajax() for more details.

Getting the data from the reply

The jQuery AJAX Tutorial may be helpful.