Processing JSON With JavaScript
Processing JSON With JavaScript
JavaScript
IT 4403 Advanced Web and Mobile
Applications
Jack G. Zheng
Fall 2019
Overview
l JSON basics
l Reading JSON file/content using
JavaScript/jQuery
2
Data Transfer/Exchange
l Data can be represented in memory in various
models or structures (relation, object, etc.), but
when it is transferred between distributed systems
and computers, it needs to be represented in plain
text files
l The process is usually called serialization
https://en.wikipedia.org/wiki/Serialization
l Popular formats
l Comma Separated Values (CSV)
https://en.wikipedia.org/wiki/Comma-separated_values
l eXtensible Markup Language (XML)
l JavaScript Object Notation (JSON)
3
JSON
l JSON (JavaScript Object Notation) is a
lightweight data format.
l It is easy for humans to read and write.
l It is easy for machines to parse and generate.
l It is based on a subset of the JavaScript
Programming Language.
4
JSON Syntax
l JSON is built on two structures:
l A collection of name/value pairs.
l An ordered list of values. In most languages, this is realized as
an array, vector, list, or sequence.
l Find detailed definition at http://www.json.org
l An object is an unordered set of name/value pairs. An object
begins with { (left brace) and ends with } (right brace). Each
name is followed by : (colon) and the name/value pairs are
separated by , (comma).
l An array is an ordered collection of values. An array begins
with [ (left bracket) and ends with ] (right bracket). Values are
separated by , (comma).
l A value can be a string in double quotes, or a number, or true
or false or null, or an object or an array. These structures can
be nested.
5
Example: A Sample JSON Document
Notice how data
are organized in
hierarchical { } for
an object. { There is no attribute concept in
JSON. “@CRN” uses @ to denote
as an attribute converted from
"Instructor": XML. This is not standard.
{
"@HireDate": "2011-08-01",
All items are in "FirstName": "Jack", Items are
name:value pairs. We separated by
use { } for a complex comma
value type, such as the
"LastName": "Zheng",
“Instructor” value
"Title": "Assistant Professor"
}
}
Names are always
enclosed by " "
6
JSON Format Examples
l Examples are provided in D2L as well as online
http://it4203.jackzheng.net/demo/json/
Files (Examples) Explanation
instructor1.json A simple example with one data item and one level of data. Note there
is no attribute node in JSON, so using @ to indicate an attribute node
from its corresponding XML format – this is not a standard.
instructor2a.json The document consists of multiple data items (records) with the same
instructor2b.json structure (three instructors). In instrcutor2b.json, a root element of
Instructors is not required actually. JSON can start with an array
directly [ ]
7
Free JSON Tools for Developers
l Recommended viewer, converter, validator
l http://jsonformatter.org
l http://codebeautify.org/jsonviewer
l JSON Viewer browser plugin
l JSONView
https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoi
hckbnefhakgolnmc (good to provide element path)
l JSON Formatter http://goo.gl/ZDLWY0
l Other JSON viewer, validator, formatter
l http://jsonlint.com/ (also try the pro version)
l http://jsonprettyprint.net/
l Converter
l http://www.utilities-online.info/xmltojson
l http://www.freeformatter.com
XML vs. JSON
JSON XML
Extended From JSON is extended from JavaScript. XML is extended from SGML : “Standard Generalized
Markup Language“.
Purpose JSON is one type of text-based format or XML is a Markup Language having format that
standard for interchanging data i.e. human contains set of rules for the encoding the documents
readable. JSON is developed by “Douglas which is readable for both human & machine. XML is
Crockford”. developed by W3C:“World Wide Web Consortium “.
Syntax JSON syntax is lighter than XML as JSON has XML is not so lighter as JSON as having start and
serialized format of data having less end tags and it takes more character than JSON to
redundancy. JSON does not contain start and represent same data.
end tags.
Speed JSON is light – weighted in compare to XML as XML is not so light weighted as JSON.
it has serialized format and so faster also.
Support of Data Type JSON supports datatype including integer and XML does not provide any data type so needs to
& Array strings, JSON also supports array. be parsed into particular datatype. No direct support
for array also.
Object Support JSON has support of native objects. XML can get support of objects through mixed use of
attributes & elements.
Comments JSON does not support Comments XML supports comments.
Namespace JSON does not have support for Namespaces. XML supports Namespaces.
Mapping JSON is data oriented and can be mapped more XML is document oriented and needs more effort
easily. for mapping.
9
Some Syntactical Differences
JSON XML
Tags JSON does not contain start and end XML is not so lighter as JSON as having start
tags. and end tags and it takes more character than
JSON to represent same data.
Attributes No attributes Has attribute node
Root element JSON may not start with a root element. There has to be a root element
It can start with an array.
Support of Data JSON supports datatype including integer XML does not provide any data type so needs
Type & Array and strings, JSON also supports array. to be parsed into particular datatype. No direct
support for array also.
Namespace JSON does not have support for XML supports Namespaces.
Namespaces.
10
Reading JSON Content
l JSON can be processed (read) by both server
side languages (PHP, C#) and client side
languages (JavaScript, jQuery)
l We will focus on the client side since this course
is more about frontend development.
l Reading JSON
l This is very simple in JavaScript as JSON is part of
JavaScript.
11
General Explanation of Examples
l Some examples need the support of PHP. So
please place these examples in a web server
(like Azure) and request them from a web
server.
l Make sure your web server serve the file types
of JSON. XML is usually supported by default. If
not supported, you will get a file not found error.
Configure the server MIME setting if necessary.
l I tried to make the examples self-explanatory.
Ask questions in class or in discussion boards.
12
Basics to Read JSON
l Use object notation to retrieve values
l Two ways to retrieve a value (assuming “json” is
the JS variable to represent a JSON object)
1. json.Instructor
Use this method to deal with special characters
2. json[“Instructor”] in names like space, : @, #, -, _, and dynamic
field name
http://stackoverflow.com/questions/4925760/sele
cting-a-json-object-with-a-colon-in-the-key
l Read from an array
l json.Instructor[0]
13
Reading JSON Examples
Files (Examples) Explanation
read-json-1.html JSON content is stored as a native JS object. Then use jQuery to read
the data and display it on the page.
read-json-2.html This example is similar to the first one except that JSON content is
stored as a string in a JS variable.
read-json-3.html This time we use an AJAJ (AJAX) way to load the file without the help
of PHP. Your server needs to be configured to be able to serve JSON
type files. This is just for your reference if you have more time. We will
cover more details on this type of techniques in the future module.
read-json-4.php For this example, we try to load the file at the server side and dump all
its content to a JavaScript variable; we do this using PHP. We then use
traditional JS to read JSON content.
read-json-5.php This is very similar to the last example, except we use jQuery. The way
how it refers to different parts of the JSON content is the same.
15
A Note on Azure
l Create a “web.config” file with the following lines
to enable JSON serving.
l https://blogs.msdn.microsoft.com/africaapps/2013/06/
07/how-to-serve-static-json-files-from-a-windows-
azure-website/
<?xml version="1.0"?>
<configuration>
<system.webServer>
<staticContent>
<mimeMap fileExtension=".json"
mimeType="application/json" />
</staticContent>
</system.webServer>
</configuration>
16
Error Handling and Debugging
l Common errors
l Spelling mistakes
l Wrong hierarchy
l Missing element
l Null value
l Special character
17
Learning Materials and Resources
l Core learning resources
l A brief intro: https://beginnersbook.com/2015/04/json-tutorial/
l A really good video tutorial:
https://www.youtube.com/watch?v=iiADhChRriM
l Try some live practice: http://www.w3schools.com/js/js_json.asp
l https://www.w3schools.com/js/js_json_intro.asp: from “Intro” to
“Arrays” section on the left menu (you may read the rest but we are
covering them in other modules).