Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
JavaScript and JSON Essentials

You're reading from   JavaScript and JSON Essentials Build light weight, scalable, and faster web applications with the power of JSON

Arrow left icon
Product type Paperback
Published in Apr 2018
Publisher
ISBN-13 9781788624701
Length 226 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Sai S Sriparasa Sai S Sriparasa
Author Profile Icon Sai S Sriparasa
Sai S Sriparasa
Bruno Joseph D'mello Bruno Joseph D'mello
Author Profile Icon Bruno Joseph D'mello
Bruno Joseph D'mello
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Getting Started with JSON FREE CHAPTER 2. The JSON Structures 3. AJAX Requests with JSON 4. Cross-Domain Asynchronous Requests 5. Debugging JSON 6. Building the Carousel Application 7. Alternate Implementations of JSON 8. Introduction to hapi.js 9. Storing JSON Documents in MongoDB 10. Configuring the Task Runner Using JSON 11. JSON for Real-Time and Distributed Data 12. Case Studies in JSON 13. Other Books You May Enjoy

The Hello World program with JSON

Now that we have a basic understanding of JSON, let us work on our Hello World program. This is shown in the snippet that follows:

<!DOCTYPE html>
<html>
<head>
<title>Test Javascript</title>
<script type="text/javascript">
let hello_world = {"Hello":"World"};
alert(hello_world.Hello);
</script>
</head>
<body>
<h2>JSON Hello World</h2>
<p>This is a test program to alert Hello world!</p>
</body>
</html>

The preceding program will display Hello World on the screen when it is invoked from a browser.

We are using let, which is a new ecmascript identifier. It differs from the normal variable declaration identifier, var, with respect to scoping. The former is scoped to the nearest function block while the latter is scoped to the nearest enclosing block. For more details please refer to the following URL: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let.

Let us pay close attention to the script between the <script> tags:

let hello_world = {"Hello":"World"};
alert(hello_world.Hello);

In the first step, we are creating a JavaScript variable and initializing the variable with a JavaScript object. Similar to how we retrieve data from a JavaScript object, we use the key-value pair to retrieve the value. Simply put, JSON is a collection of key and value pairs, where every key is a reference to the memory location where the value is stored on the computer. Now let us take a step back and analyse why we need JSON if all we are doing is assigning JavaScript objects that are readily available. The answer is, JSON is a different format altogether, unlike JavaScript, which is a language.

JSON keys and values have to be enclosed in double quotes. If either is enclosed in single quotes, we will receive an error.

Now, let us take a quick look at the similarities and differences between JSON and a normal JavaScript object. If we were to create a similar JavaScript object like our hello_world JSON variable from the earlier example, it would look like the JavaScript object that follows:

let hello_world = {"Hello":"World"};

The big difference here is that the key is not wrapped in double quotes. Since JSON key is a string, we can use any valid string for a key. We can use spaces, special characters, and hyphens in our keys, none of which are valid in a normal JavaScript object:

let hello_world = {"test-hello":"World"};

When we use special characters, hyphens, or spaces in our keys, we have to be careful while accessing them:

alert(hello_world.test-hello); //doesn't work

The reason the preceding JavaScript statement doesn't work is that JavaScript doesn't accept keys with special characters, hyphens, or strings. So, we have to retrieve the data using a method where we will handle the JSON object as an associative array with a string key. This is shown in the snippet that follows:

alert(hello_world["test-hello"]); //Hurray! It work

Another difference between the two is that a JavaScript object can carry functions within, while JSON object cannot carry any functions. The example that follows has the property getFullName, which has a function that alerts the name John Doe when it is invoked:

{
"studentid" : 101,
"firstname" : "John",
"lastname" : "Doe",
"isStudent" : true,
"classes" : [
"Business Research",
"Economics",
"Finance"
],
"getFullName" : function(){
alert(`${this.firstname} ${this.lastname}`);
}
}
Note that the string interpolation feature is a new ES feature that can be used when writing variables and functions inside the expression `${}`. The expression only works in tilde inverted commas and not in other types of inverted commas.

Finally, the biggest difference is that a JavaScript object was never intended to be a data interchange format, while the sole purpose of JSON was to act as a data interchange format.

In the upcoming section, we are going to learn about JSON memory allocation.

You have been reading a chapter from
JavaScript and JSON Essentials - Second Edition
Published in: Apr 2018
Publisher:
ISBN-13: 9781788624701
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image