Unit 2 Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

Unit 2

XML and JSON

Introduction to XML

• XML stands for eXtensible Markup Language


• XML is a markup language much like HTML
• XML was designed to store and transport data
• XML was designed to be self-descriptive

Example:

<note>

<to>Tove</to>

<from>Jani</from>

<heading>Reminder</heading>

<body>Don't forget me this weekend!</body>

</note>

The XML above is quite self-descriptive:

• It has sender information


• It has receiver information
• It has a heading
• It has a message body

But still, the XML above does not DO anything. XML is just information wrapped in
tags.

The Difference Between XML and HTML

XML and HTML were designed with different goals:

• XML was designed to carry data - with focus on what data is

• HTML was designed to display data - with focus on how data looks

• XML tags are not predefined like HTML tags are


XML Does Not Use Predefined Tags

• The XML language has no predefined tags.


• The tags in the example above (like <to> and <from>) are not defined in any
XML standard. These tags are "invented" by the author of the XML document.
• HTML works with predefined tags like <p>, <h1>, <table>, etc.
• With XML, the author must define both the tags and the document structure.

XML Simplifies Things

• XML simplifies data sharing

• XML simplifies data transport

• XML simplifies platform changes

• XML simplifies data availability

• Many computer systems contain data in incompatible formats. Exchanging


data between incompatible systems (or upgraded systems) is a time-
consuming task for web developers. Large amounts of data must be converted,
and incompatible data is often lost.
• XML stores data in plain text format. This provides a software- and hardware-
independent way of storing, transporting, and sharing data.
• XML also makes it easier to expand or upgrade to new operating systems, new
applications, or new browsers, without losing data.
• With XML, data can be available to all kinds of "reading machines" like people,
computers, voice machines, news feeds, etc.
XML Fundamentals

XML Tree

• XML documents form a tree structure that starts at "the root" and branches to "the
leaves".

The XML Tree Structure

An Example XML Document

• The image above represents books in this XML:

<?xml version="1.0" encoding="UTF-8"?>


<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

XML Tree Structure

• XML documents are formed as element trees.


• An XML tree starts at a root element and branches from the root to child
elements.
• All elements can have sub elements (child elements):

<root>
<child>
<subchild>.....</subchild>
</child>
</root>

• The terms parent, child, and sibling are used to describe the relationships between
elements.
• Parents have children. Children have parents. Siblings are children on the same
level (brothers and sisters).
• All elements can have text content (Harry Potter) and attributes
(category="cooking").

Self-Describing Syntax

• XML uses a much self-describing syntax.


• A prolog defines the XML version and the character encoding:
• <?xml version="1.0" encoding="UTF-8"?>
• The next line is the root element of the document:

<bookstore>

• The next line starts a <book> element:

<book category="cooking">

• The <book> elements have 4 child elements:


✓ <title>
✓ <author>
✓ <year>
✓ <price>.

<title lang="en">Everyday Italian</title>


<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>

• The next line ends the book element:

</book>

XML Syntax Rules

• The syntax rules of XML are very simple and logical. The rules are easy to learn,
and easy to use.

XML Documents Must Have a Root Element

• XML documents must contain one root element that is the parent of all other
elements:

<root>
<child>
<subchild>.....</subchild>
</child>
</root>

• In this example <note> is the root element:


<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

The XML Prolog

• This line is called the XML prolog:


<?xml version="1.0" encoding="UTF-8"?>
• The XML prolog is optional. If it exists, it must come first in the document.
• To avoid errors, you should specify the encoding used, or save your XML files as
UTF-8.
• UTF-8 is the default character encoding for XML documents.
• UTF-8 is also the default encoding for HTML5, CSS, JavaScript, PHP, and SQL.

All XML Elements Must Have a Closing Tag

• In XML, it is illegal to omit the closing tag. All elements must have a closing tag:

<p>This is a paragraph.</p>
<br />

• Note: The XML prolog does not have a closing tag! This is not an error. The prolog
is not a part of the XML document.

XML Tags are Case Sensitive

• XML tags are case sensitive. The tag <Letter> is different from the tag <letter>.
• Opening and closing tags must be written with the same case:
<message>This is correct</message>
• "Opening and closing tags" are often referred to as "Start and end tags". Use
whatever you prefer. It is exactly the same thing.
XML Elements Must be Properly Nested

• In HTML, you might see improperly nested elements:


<b><i>This text is bold and italic</b></i>
• In XML, all elements must be properly nested within each other:
<b><i>This text is bold and italic</i></b>
• In the example above, "Properly nested" simply means that since the <i> element
is opened inside the <b> element, it must be closed inside the <b> element.

XML Attribute Values Must Always be Quoted

• XML elements can have attributes in name/value pairs just like in HTML.
• In XML, the attribute values must always be quoted:

<note date="12/11/2007">
<to>Tove</to>
<from>Jani</from>
</note>

Entity References

• Some characters have a special meaning in XML.


• If you place a character like "<" inside an XML element, it will generate an error
because the parser interprets it as the start of a new element.
• This will generate an XML error:

<message>salary < 1000</message>

• To avoid this error, replace the "<" character with an entity reference:

<message>salary &lt; 1000</message>

• There are 5 pre-defined entity references in XML:

&lt; < less than

&gt; > greater than

&amp; & ampersand


&apos; ' apostrophe

&quot; " quotation mark

• Only < and & are strictly illegal in XML, but it is a good habit to replace > with &gt;
as well.

Comments in XML

• The syntax for writing comments in XML is similar to that of HTML:

<!-- This is a comment -->

• Two dashes in the middle of a comment are not allowed:

<!-- This is an invalid -- comment -->

White-space is Preserved in XML

• XML does not truncate multiple white-spaces (HTML truncates multiple white-
spaces to one single white-space):

XML: Hello Tove

HTML: Hello Tove

XML Stores New Line as LF

• Windows applications store a new line as: carriage return and line feed (CR+LF).
• Unix and Mac OSX use LF.
• Old Mac systems use CR.
• XML stores a new line as LF.

Well Formed XML

• XML documents that conform to the syntax rules above are said to be "Well
Formed" XML documents.
XML Elements

• An XML document contains XML Elements.

What is an XML Element?

• An XML element is everything from (including) the element's start tag to


(including) the element's end tag.

<price>29.99</price>

• An element can contain:


✓ text
✓ attributes
✓ other elements
✓ or a mix of the above

<bookstore>
<book category="children">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

• In the example above:


o <title>, <author>, <year>, and <price> have text content because they
contain text (like 29.99).
o <bookstore> and <book> have element contents, because they contain
elements.
o <book> has an attribute (category="children").

Empty XML Elements

• An element with no content is said to be empty.


• In XML, you can indicate an empty element like this:

<element></element>

• You can also use a so called self-closing tag:

<element />

• The two forms produce identical results in XML software (Readers, Parsers,
Browsers).
• Empty elements can have attributes.

XML Naming Rules

XML elements must follow these naming rules:

• Element names are case-sensitive


• Element names must start with a letter or underscore
• Element names cannot start with the letters xml (or XML, or Xml, etc)
• Element names can contain letters, digits, hyphens, underscores, and periods
• Element names cannot contain spaces

Any name can be used, no words are reserved (except xml).

Best Naming Practices

• Create descriptive names, like this: <person>, <firstname>, <lastname>.


• Create short and simple names, like this: <book_title> not like this:
<the_title_of_the_book>.
• Avoid "-". If you name something "first-name", some software may think you want
to subtract "name" from "first".
• Avoid ".". If you name something "first.name", some software may think that
"name" is a property of the object "first".
• Avoid ":". Colons are reserved for namespaces (more later).
Naming Conventions

• Some commonly used naming conventions for XML elements:

Style Example Description

Lower
<firstname> All letters lower case
case

Upper
<FIRSTNAME> All letters upper case
case

Snake Underscore separates words (commonly used in SQL


<first_name>
case databases)

Pascal Uppercase first letter in each word (commonly used by C


<FirstName>
case programmers)

Camel Uppercase first letter in each word except the first


<firstName>
case (commonly used in JavaScript)

XML Attributes

• XML elements can have attributes, just like HTML.


• Attributes are designed to contain data related to a specific element.

XML Attributes Must be Quoted

• Attribute values must always be quoted. Either single or double quotes can be
used.
• For a person's gender, the <person> element can be written like this:
<person gender="female">
• or like this:
<person gender='female'>
• If the attribute value itself contains double quotes you can use single quotes, like
in this example:
<gangster name='George "Shotgun" Ziegler'>

• or you can use character entities:

<gangster name="George &quot;Shotgun&quot; Ziegler">

---------------------------------------------------------------------------------------------------------------

XML DTD

• An XML document with correct syntax is called "Well Formed".


• An XML document validated against a DTD is both "Well Formed" and "Valid".

What is a DTD?

• DTD stands for Document Type Definition.


• A DTD defines the structure and the legal elements and attributes of an XML
document.

Valid XML Documents

• A "Valid" XML document is "Well Formed", as well as it conforms to the rules of a


DTD:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE note SYSTEM "Note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

• The DOCTYPE declaration above contains a reference to a DTD file. The content of
the DTD file is shown and explained below.

XML DTD

• The purpose of a DTD is to define the structure and the legal elements and
attributes of an XML document:
Note.dtd:

<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>

• The DTD above is interpreted like this:


o !DOCTYPE note - Defines that the root element of the document is note
o !ELEMENT note - Defines that the note element must contain the elements: "to,
from, heading, body"
o !ELEMENT to - Defines the to element to be of type "#PCDATA"
o !ELEMENT from - Defines the from element to be of type "#PCDATA"
o !ELEMENT heading - Defines the heading element to be of type "#PCDATA"
o !ELEMENT body - Defines the body element to be of type "#PCDATA"

Using DTD for Entity Declaration

• A DOCTYPE declaration can also be used to define special characters or strings,


used in the document:

Example

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE note [
<!ENTITY nbsp "&#xA0;">
<!ENTITY writer "Writer: Donald Duck.">
<!ENTITY copyright "Copyright: W3Schools.">
]>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<footer>&writer;&nbsp;&copyright;</footer>
</note>

When to Use a DTD?

• With a DTD, independent groups of people can agree to use a standard DTD for
interchanging data.
• With a DTD, you can verify that the data you receive from the outside world is
valid.
• You can also use a DTD to verify your own data

When NOT to Use a DTD?

• XML does not require a DTD.


• When you are experimenting with XML, or when you are working with small XML
files, creating DTDs may be a waste of time.
• If you develop applications, wait until the specification is stable before you add a
DTD. Otherwise, your software might stop working because of validation errors.

--------------------------------------------------------------------------------------------------------------

XML Schema

• An XML Schema describes the structure of an XML document, just like a DTD.
• An XML document with correct syntax is called "Well Formed".
• An XML document validated against an XML Schema is both "Well Formed" and
"Valid".

XML Schema

XML Schema is an XML-based alternative to DTD:

<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

• The Schema above is interpreted like this:

o <xs:element name="note"> defines the element called "note"

o <xs:complexType> the "note" element is a complex type

o <xs:sequence> the complex type is a sequence of elements

o <xs:element name="to" type="xs:string"> the element "to" is of type string


(text)

o <xs:element name="from" type="xs:string"> the element "from" is of type


string

o <xs:element name="heading" type="xs:string"> the element "heading" is of


type string

o <xs:element name="body" type="xs:string"> the element "body" is of type


string

XML Schemas are More Powerful than DTD

• XML Schemas are written in XML


• XML Schemas are extensible to additions
• XML Schemas support data types
• XML Schemas support namespaces

Why Use an XML Schema?

• With XML Schema, your XML files can carry a description of its own format.
• With XML Schema, independent groups of people can agree on a standard for
interchanging data.
• With XML Schema, you can verify data.
XML Schemas Support Data Types

One of the greatest strengths of XML Schemas is the support for data types:

• It is easier to describe document content


• It is easier to define restrictions on data
• It is easier to validate the correctness of data
• It is easier to convert data between different data types

XML Schemas use XML Syntax

Another great strength about XML Schemas is that they are written in XML:

• You don't have to learn a new language


• You can use your XML editor to edit your Schema files
• You can use your XML parser to parse your Schema files
• You can manipulate your Schemas with the XML DOM
• You can transform your Schemas with XSLT

-----------------------------------------------------------------------------------------------------------------

XML Namespaces

• XML Namespaces provide a method to avoid element name conflicts.

Name Conflicts

• In XML, element names are defined by the developer. This often results in a conflict
when trying to mix XML documents from different XML applications.
• This XML carries HTML table information:

<table>

<tr>

<td>Apples</td>

<td>Bananas</td>

</tr>

</table>
• This XML carries information about a table (a piece of furniture):

<table>

<name>African Coffee Table</name>

<width>80</width>

<length>120</length>

</table>

• If these XML fragments were added together, there would be a name conflict. Both
contain a <table> element, but the elements have different content and meaning.
• A user or an XML application will not know how to handle these differences.
• Solving the Name Conflict Using a Prefix
• Name conflicts in XML can easily be avoided using a name prefix.
• This XML carries information about an HTML table, and a piece of furniture:

<h:table>

<h:tr>

<h:td>Apples</h:td>

<h:td>Bananas</h:td>

</h:tr>

</h:table>

<f:table>

<f:name>African Coffee Table</f:name>

<f:width>80</f:width>

<f:length>120</f:length>

</f:table>
• In the example above, there will be no conflict because the two <table> elements
have different names.

XML Namespaces - The xmlns Attribute

• When using prefixes in XML, a namespace for the prefix must be defined.
• The namespace can be defined by an xmlns attribute in the start tag of an element.
• The namespace declaration has the following syntax. xmlns:prefix="URI".

<root>

<h:table xmlns:h="http://www.w3.org/TR/html4/">

<h:tr>

<h:td>Apples</h:td>

<h:td>Bananas</h:td>

</h:tr>

</h:table>

<f:table xmlns:f="https://www.w3schools.com/furniture">

<f:name>African Coffee Table</f:name>

<f:width>80</f:width>

<f:length>120</f:length>

</f:table>

</root>

In the example above:

• The xmlns attribute in the first <table> element gives the h: prefix a qualified
namespace.
• The xmlns attribute in the second <table> element gives the f: prefix a qualified
namespace.
• When a namespace is defined for an element, all child elements with the same
prefix are associated with the same namespace.
• Namespaces can also be declared in the XML root element:

<root xmlns:h="http://www.w3.org/TR/html4/"

xmlns:f="https://www.w3schools.com/furniture">

<h:table>

<h:tr>

<h:td>Apples</h:td>

<h:td>Bananas</h:td>

</h:tr>

</h:table>

<f:table>

<f:name>African Coffee Table</f:name>

<f:width>80</f:width>

<f:length>120</f:length>

</f:table>

</root>

• The purpose of using an URI is to give the namespace a unique name.


• However, companies often use the namespace as a pointer to a web page
containing namespace information.

Uniform Resource Identifier (URI)

• A Uniform Resource Identifier (URI) is a string of characters which identifies an


Internet Resource.
• The most common URI is the Uniform Resource Locator (URL) which identifies an
Internet domain address. Another, not so common type of URI is the Uniform
Resource Name (URN).
Default Namespaces

• Defining a default namespace for an element saves us from using prefixes in all the
child elements. It has the following syntax:

xmlns="namespaceURI"

• This XML carries HTML table information:

<table xmlns="http://www.w3.org/TR/html4/">

<tr>

<td>Apples</td>

<td>Bananas</td>

</tr>

</table>

• This XML carries information about a piece of furniture:

<table xmlns="https://www.w3schools.com/furniture">

<name>African Coffee Table</name>

<width>80</width>

<length>120</length>

</table>

Namespaces in Real Use

• XSLT is a language that can be used to transform XML documents into other
formats.
• The XML document below, is a document used to transform XML into HTML.
• The namespace "http://www.w3.org/1999/XSL/Transform" identifies XSLT
elements inside an HTML document:

<?xml version="1.0" encoding="UTF-8"?>

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>

<body>

<h2>My CD Collection</h2>

<table border="1">

<tr>

<th style="text-align:left">Title</th>

<th style="text-align:left">Artist</th>

</tr>

<xsl:for-each select="catalog/cd">

<tr>

<td><xsl:value-of select="title"/></td>

<td><xsl:value-of select="artist"/></td>

</tr>

</xsl:for-each>

</table>

</body>

</html>

</xsl:template>

</xsl:stylesheet>

-----------------------------------------------------------------------------------------------------------------

XPath

What is XPath?

• XPath is a major element in the XSLT standard.


• XPath can be used to navigate through elements and attributes in an XML
document.
• XPath is a syntax for defining parts of an XML document

• XPath uses path expressions to navigate in XML


documents

• XPath contains a library of standard functions

• XPath is a major element in XSLT and in XQuery

• XPath is a W3C recommendation

XPath Path Expressions

• XPath uses path expressions to select nodes or node-sets in an XML document.


These path expressions look very much like the expressions you see when you
work with a traditional computer file system.
• XPath expressions can be used in JavaScript, Java, XML Schema, PHP, Python, C and
C++, and lots of other languages.

XPath is Used in XSLT

• XPath is a major element in the XSLT standard.


• With XPath knowledge you will be able to take great advantage of XSL.

XPath Example

• We will use the following XML document:

<?xml version="1.0" encoding="UTF-8"?>


<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

• In the table below we have listed some XPath expressions and the result of the
expressions:

XPath Expression Result

Selects the first book element that is the child of the


/bookstore/book[1]
bookstore element

Selects the last book element that is the child of the


/bookstore/book[last()]
bookstore element

Selects the last but one book element that is the


/bookstore/book[last()-1]
child of the bookstore element
Selects the first two book elements that are
/bookstore/book[position()<3]
children of the bookstore element

Selects all the title elements that have an attribute


//title[@lang]
named lang

Selects all the title elements that have a "lang"


//title[@lang='en']
attribute with a value of "en"

Selects all the book elements of the bookstore


/bookstore/book[price>35.00] element that have a price element with a value
greater than 35.00

Selects all the title elements of the book elements


/bookstore/book[price>35.00]/title of the bookstore element that have a price element
with a value greater than 35.00

---------------------------------------------------------------------------------------------------------------

XSLT

• With XSLT you can transform an XML document into HTML.

Displaying XML with XSLT

• XSLT (eXtensible Stylesheet Language Transformations) is the recommended


style sheet language for XML.

• XSLT is far more sophisticated than CSS. With XSLT you can add/remove elements
and attributes to or from the output file. You can also rearrange and sort elements,
perform tests and make decisions about which elements to hide and display, and
a lot more.
• XSLT uses XPath to find information in an XML document.

XSLT Example

• We will use the following XML document:

<?xml version="1.0" encoding="UTF-8"?>


<breakfast_menu>

<food>

<name>Belgian Waffles</name>

<price>$5.95</price>

<description>Two of our famous Belgian Waffles with plenty of real maple


syrup</description>

<calories>650</calories>

</food>

<food>

<name>Strawberry Belgian Waffles</name>

<price>$7.95</price>

<description>Light Belgian waffles covered with strawberries and


whipped cream</description>

<calories>900</calories>

</food>

<food>

<name>Berry-Berry Belgian Waffles</name>

<price>$8.95</price>

<description>Light Belgian waffles covered with an assortment of fresh


berries and whipped cream</description>

<calories>900</calories>

</food>

<food>

<name>French Toast</name>

<price>$4.50</price>
<description>Thick slices made from our homemade sourdough
bread</description>

<calories>600</calories>

</food>

<food>

<name>Homestyle Breakfast</name>

<price>$6.95</price>

<description>Two eggs, bacon or sausage, toast, and our ever-popular hash


browns</description>

<calories>950</calories>

</food>

</breakfast_menu>

• Use XSLT to transform XML into HTML, before it is displayed in a browser:


• Example XSLT Stylesheet:

<?xml version="1.0" encoding="UTF-8"?>

<html xsl:version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<body style="font-family:Arial;font-size:12pt;background-
color:#EEEEEE">

<xsl:for-each select="breakfast_menu/food">

<div style="background-color:teal;color:white;padding:4px">

<span style="font-weight:bold"><xsl:value-of select="name"/> -


</span>

<xsl:value-of select="price"/>

</div>

<div style="margin-left:20px;margin-bottom:1em;font-size:10pt">

<p>

<xsl:value-of select="description"/>
<span style="font-style:italic"> (<xsl:value-of select="calories"/>
calories per serving)</span>

</p>

</div>

</xsl:for-each>

</body>

</html>

-----------------------------------------------------------------------------------------------------------------

JSON - Introduction

• JSON stands for JavaScript Object Notation


• JSON is a lightweight data-interchange format
• JSON is plain text written in JavaScript object notation
• JSON is used to send data between computers
• JSON is language independent

JSON Example

This example is a JSON string:

'{"name":"John", "age":30, "car":null}'

• It defines an object with 3 properties:


o name
o age
o car
• Each property has a value.
• If you parse the JSON string with a JavaScript program, you can access the data as
an object:

let personName = obj.name;


let personAge = obj.age;
Why Use JSON?

• The JSON format is syntactically similar to the code for creating JavaScript objects.
Because of this, a JavaScript program can easily convert JSON data into JavaScript
objects.
• Since the format is text only, JSON data can easily be sent between computers, and
used by any programming language.
• JavaScript has a built in function for converting JSON strings into JavaScript
objects:

JSON.parse()

• JavaScript also has a built in function for converting an object into a JSON string:

JSON.stringify()

• You can receive pure text from a server and use it as a JavaScript object.
• You can send a JavaScript object to a server in pure text format.
• You can work with data as JavaScript objects, with no complicated parsing and
translations.

Storing Data

• When storing data, the data has to be a certain format, and regardless of where
you choose to store it, text is always one of the legal formats.
• JSON makes it possible to store JavaScript objects as text

JSON Syntax

• The JSON syntax is a subset of the JavaScript syntax.

JSON Syntax Rules

• JSON syntax is derived from JavaScript object notation syntax:


o Data is in name/value pairs
o Data is separated by commas
o Curly braces hold objects
o Square brackets hold arrays
JSON Data - A Name and a Value

• JSON data is written as name/value pairs (aka key/value pairs).


• A name/value pair consists of a field name (in double quotes), followed by a colon,
followed by a value:

Example

"name":"John"

• JSON names require double quotes.

JSON - Evaluates to JavaScript Objects

• The JSON format is almost identical to JavaScript objects.


• In JSON, keys must be strings, written with double quotes:

JSON

{"name":"John"}

• In JavaScript, keys can be strings, numbers, or identifier names:

JavaScript

{name:"John"}

JSON Values

• In JSON, values must be one of the following data types:


o a string
o a number
o an object
o an array
o a boolean
o null
• In JavaScript values can be all of the above, plus any other valid JavaScript
expression, including:
o a function
o a date
o undefined
• In JSON, string values must be written with double quotes:

JSON

{"name":"John"}

In JavaScript, you can write string values with double or single quotes:

JavaScript

{name:'John'}

JavaScript Objects

• Because JSON syntax is derived from JavaScript object notation, very little extra
software is needed to work with JSON within JavaScript.
• With JavaScript you can create an object and assign data to it, like this:

Example

person = {name:"John", age:31, city:"New York"};

• You can access a JavaScript object like this:

Example

// returns John
person.name;

• It can also be accessed like this:

Example

// returns John
person["name"];

• Data can be modified like this:

Example

person.name = "Gilbert";

• It can also be modified like this:


Example

person["name"] = "Gilbert";

• You will learn how to convert JavaScript objects into JSON later in this tutorial.

JavaScript Arrays as JSON

• The same way JavaScript objects can be written as JSON, JavaScript arrays can also
be written as JSON.

JSON Files

• The file type for JSON files is ".json"


• The MIME type for JSON text is "application/json"

JSON Data Types

In JSON, values must be one of the following data types:

• a string
• a number
• an object (JSON object)
• an array
• a Boolean
• null

JSON values cannot be one of the following data types:

• a function
• a date
• undefined

JSON Strings

• Strings in JSON must be written in double quotes.

Example

{"name":"John"}
JSON Numbers

• Numbers in JSON must be an integer or a floating point.

Example

{"age":30}

JSON Objects

• Values in JSON can be objects.

Example

{
"employee":{"name":"John", "age":30, "city":"New York"}
}

• Objects as values in JSON must follow the JSON syntax.

JSON Arrays

• Values in JSON can be arrays.

Example

{
"employees":["John", "Anna", "Peter"]
}

JSON Booleans

• Values in JSON can be true/false.

Example

{"sale":true}

JSON null

• Values in JSON can be null.

Example

{"middlename":null}
JSON.parse()

• A common use of JSON is to exchange data to/from a web server.


• When receiving data from a web server, the data is always a string.
• Parse the data with JSON.parse(), and the data becomes a JavaScript object.

Example - Parsing JSON

• Imagine we received this text from a web server:

'{"name":"John", "age":30, "city":"New York"}'

• Use the JavaScript function JSON.parse() to convert text into a JavaScript object:

const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');

• Make sure the text is in JSON format, or else you will get a syntax error.
• Use the JavaScript object in your page:

Example

<p id="demo"></p>
<script>document.getElementById("demo").innerHTML = obj.name;
</script>

JSON.stringify()

• A common use of JSON is to exchange data to/from a web server.


• When sending data to a web server, the data has to be a string.
• Convert a JavaScript object into a string with JSON.stringify().

Stringify a JavaScript Object

• Imagine we have this object in JavaScript:

const obj = {name: "John", age: 30, city: "New York"};

• Use the JavaScript function JSON.stringify() to convert it into a string.

const myJSON = JSON.stringify(obj);

• The result will be a string following the JSON notation.


• myJSON is now a string, and ready to be sent to a server:
Example

const obj = {name: "John", age: 30, city: "New York"};


const myJSON = JSON.stringify(obj);

• You will learn how to send JSON to a server in the next chapters.

Stringify a JavaScript Array

• It is also possible to stringify JavaScript arrays:


• Imagine we have this array in JavaScript:

const arr = ["John", "Peter", "Sally", "Jane"];

• Use the JavaScript function JSON.stringify() to convert it into a string.

const myJSON = JSON.stringify(arr);

• The result will be a string following the JSON notation.


• myJSON is now a string, and ready to be sent to a server:

Example

const arr = ["John", "Peter", "Sally", "Jane"];


const myJSON = JSON.stringify(arr);

Storing Data

• When storing data, the data has to be a certain format, and regardless of where
you choose to store it, text is always one of the legal formats.
• JSON makes it possible to store JavaScript objects as text.

Example

• Storing data in local storage

// Storing data:
const myObj = {name: "John", age: 31, city: "New York"};
const myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);

// Retrieving data:
let text = localStorage.getItem("testJSON");
let obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;

JSON Object

• This is a JSON string:

'{"name":"John", "age":30, "car":null}'

• Inside the JSON string there is a JSON object literal:

{"name":"John", "age":30, "car":null}

• JSON object literals are surrounded by curly braces {}.


• JSON object literals contains key/value pairs.
• Keys and values are separated by a colon.
• Keys must be strings, and values must be a valid JSON data type:
o string
o number
o object
o array
o boolean
o null
• Each key/value pair is separated by a comma.
• It is a common mistake to call a JSON object literal "a JSON object".
• JSON cannot be an object. JSON is a string format.
• The data is only JSON when it is in a string format. When it is converted to a
JavaScript variable, it becomes a JavaScript object.

JavaScript Objects

• You can create a JavaScript object from a JSON object literal:

Example

• myObj = {"name":"John", "age":30, "car":null};

Normally, you create a JavaScript object by parsing a JSON string:


Example

myJSON = '{"name":"John", "age":30, "car":null}';


myObj = JSON.parse(myJSON);

Accessing Object Values

• You can access object values by using dot (.) notation:

Example

const myJSON = '{"name":"John", "age":30, "car":null}';


const myObj = JSON.parse(myJSON);
x = myObj.name;

• You can also access object values by using bracket ([]) notation:

Example

const myJSON = '{"name":"John", "age":30, "car":null}';


const myObj = JSON.parse(myJSON);
x = myObj["name"];

Looping an Object

• You can loop through object properties with a for-in loop:

Example

const myJSON = '{"name":"John", "age":30, "car":null}';


const myObj = JSON.parse(myJSON);
let text = "";
for (const x in myObj) {
text += x + ", ";
}

• In a for-in loop, use the bracket notation to access the property values:
Example

const myJSON = '{"name":"John", "age":30, "car":null}';


const myObj = JSON.parse(myJSON);

let text = "";


for (const x in myObj) {
text += myObj[x] + ", ";
}

JSON Array

• This is a JSON string:

'["Ford", "BMW", "Fiat"]'

• Inside the JSON string there is a JSON array literal:

["Ford", "BMW", "Fiat"]

• Arrays in JSON are almost the same as arrays in JavaScript.


• In JSON, array values must be of type string, number, object, array, boolean or null.
• In JavaScript, array values can be all of the above, plus any other valid JavaScript
expression, including functions, dates, and undefined.

JavaScript Arrays

• You can create a JavaScript array from a literal:

Example

myArray = ["Ford", "BMW", "Fiat"];


• You can create a JavaScript array by parsing a JSON string:

Example

myJSON = '["Ford", "BMW", "Fiat"]';


myArray = JSON.parse(myJSON);

Accessing Array Values

• You access array values by index:


Example

myArray[0];

Arrays in Objects

• Objects can contain arrays:

Example

{
"name":"John",
"age":30,
"cars":["Ford", "BMW", "Fiat"]
}

• You access array values by index:

Example

myObj.cars[0];

Looping Through an Array

• You can access array values by using a for in loop:

Example

for (let i in myObj.cars) {


x += myObj.cars[i];
}

• Or you can use a for loop:

Example

for (let i = 0; i < myObj.cars.length; i++) {


x += myObj.cars[i];
}

You might also like