You are on page 1of 14

Introduction

JSON — short for JavaScript Object Notation — is a format for sharing data.
As its name suggests, JSON is derived from the JavaScript programming
language, but it’s available for use by many languages including Python, Ruby,
PHP, and Java. JSON is usually pronounced like the name “Jason.”

JSON uses the .json extension when it stands alone. When it’s defined in
another file format (as in .html), it can appear inside of quotes as a JSON
string, or it can be an object assigned to a variable. This format is easy to
transmit between web server and client or browser.

Very readable and lightweight, JSON offers a good alternative to XML and
requires much less formatting. This informational guide will get you up to speed
with the data you can use in JSON files, and the general structure and syntax of
this format.

Syntax and Structure


A JSON object is a key-value data format that is typically rendered in curly
braces. When you’re working with JSON, you’ll likely see JSON objects in a
.json file, but they can also exist as a JSON object or string within the context
of a program.

A JSON object looks something like this:

{
"first_name" : "Sammy",
"last_name" : "Shark",
"location" : "Ocean",
"online" : true,
"followers" : 987
}

Although this is a very short example, and JSON could be many lines long, this
shows that the format is generally set up with two curly braces (or curly
brackets) that look like this { } on either end of it, and with key-value pairs
populating the space between. Most data used in JSON ends up being
encapsulated in a JSON object.

Key-value pairs have a colon between them as in "key" : "value". Each key-
value pair is separated by a comma, so the middle of a JSON looks like this:
"key" : "value", "key" : "value", "key": "value". In our example
above, the first key-value pair is "first_name" : "Sammy".

JSON keys are on the left side of the colon. They need to be wrapped in double
quotation marks, as in "key", and can be any valid string. Within each object,
keys need to be unique. These key strings can include whitespaces, as in
"first name", but that can make it harder to access when you’re
programming, so it’s best to use underscores, as in "first_name".

JSON values are found to the right of the colon. At the granular level, these
need to be one of 6 simple data types:

•strings
•numbers
•objects
•arrays
•Booleans (true or false)
•null
At the broader level, values can also be made up of the complex data types of

JSON object or array, which is covered in the next section.

Each of the data types that are passed in as values into JSON will maintain their
own syntax, so strings will be in quotes, but numbers will not be.

Though in .json files, we’ll typically see the format expanded over multiple
lines, JSON can also be written all in one line.

{ "first_name" : "Sammy", "last_name": "Shark", "online" : true, }

This would be more common within another file type or when you encounter a
JSON string.

Writing the JSON format on multiple lines often makes it much more readable,
especially when dealing with a large data set. Because JSON ignores
whitespace between its elements, you can space out your colons and key-value
pairs in order to make the data even more human readable:

{
"first_name" : "Sammy",
"last_name" : "Shark",
"online" : true
}

It is important to keep in mind that though they look similar, a JSON object is
not the same format as a JavaScript object, so, though you can use functions
within JavaScript objects, you cannot use them as values in JSON. The most
important attribute of JSON is that it can be readily transferred between
programming languages in a format that all of the participating languages can
work with. JavaScript objects can only be worked with directly through the
JavaScript programming language.

So far we have looked at the JSON format in its simplest terms, but JSON can
become hierarchical and complex, comprised of nested objects and arrays.
We’ll go over more complex JSON in the next section.

Working with Complex Types in JSON


JSON can store nested objects in JSON format in addition to nested arrays.
These objects and arrays will be passed as values assigned to keys, and
typically will be comprised of key-value pairs as well.

Nested Objects
In the users.json file below, for each of the four users ("sammy", "jesse",
"drew", "jamie") there is a nested JSON object passed as the value for each of
the users, with its own nested keys of "username" and "location" that relate
to each of the users. The first nested JSON object is highlighted below.

users.json
{
"sammy" : {
"username" : "SammyShark",
"location" : "Indian Ocean",
"online" : true,
"followers" : 987
},
"jesse" : {
"username" : "JesseOctopus",
"location" : "Pacific Ocean",
"online" : false,
"followers" : 432
},
"drew" : {
"username" : "DrewSquid",
"location" : "Atlantic Ocean",
"online" : false,
"followers" : 321
},
"jamie" : {
"username" : "JamieMantisShrimp",
"location" : "Pacific Ocean",
"online" : true,
"followers" : 654
}
}

In the example above, curly braces are used throughout to form a nested JSON
object with associated username and location data for each of four users. Just
like any other value, when using objects, commas are used to separate
elements.

Nested Arrays
Data can also be nested within the JSON format by using JavaScript arrays that
are passed as a value. JavaScript uses square brackets [ ] on either end of its
array type. Arrays are ordered collections and can contain values of differing
data types.

We may use an array when we are dealing with a lot of data that can be easily
grouped together, like when there are various websites and social media
profiles associated with a single user.

With the first nested array highlighted, a user profile for Sammy may look like
this:

user_profile.json
{
"first_name" : "Sammy",
"last_name" : "Shark",
"location" : "Ocean",
"websites" : [
{
"description" : "work",
"URL" : "https://www.digitalocean.com/"
},
{
"desciption" : "tutorials",
"URL" : "https://www.digitalocean.com/community/tutorials"
}
],
"social_media" : [
{
"description" : "twitter",
"link" : "https://twitter.com/digitalocean"
},
{
"description" : "facebook",
"link" : "https://www.facebook.com/DigitalOceanCloudHosting"
},
{
"description" : "github",
"link" : "https://github.com/digitalocean"
}
]
}

The "websites" key and "social_media" key each use an array to nest
information belonging to Sammy’s 2 website links and 3 social media profile
links. We know that those are arrays because of the use of square brackets.

Using nesting within our JSON format lets us work with more complicated and
hierarchical
Examples of JSON

Example

// Store JSON data in a JS variable


var json = '{"name": "Peter", "age": 22, "country": "United States"}';

// Converting JSON-encoded string to JS object


var obj = JSON.parse(json);

// Accessing individual value from JS object


alert(obj.name); // Outputs: Peter
alert(obj.age); // Outputs: 22
alert(obj.country); // Outputs: United States

Parsing Nested JSON Data in JavaScript


JSON objects and arrays can also be nested. A JSON object can arbitrarily
contains other JSON objects, arrays, nested arrays, arrays of JSON objects, and
so on. The following example will show you how to parse a nested JSON object
and extract all the values in JavaScript.

Example
/* Storing multi-line JSON string in a JS variable
using the new ES6 template literals */
var json = `{
"book": {
"name": "Harry Potter and the Goblet of Fire",
"author": "J. K. Rowling",
"year": 2000,
"characters": ["Harry Potter", "Hermione Granger", "Ron
Weasley"],
"genre": "Fantasy Fiction",
"price": {
"paperback": "$10.40", "hardcover": "$20.32", "kindle":
"$4.11"
}
}
}`;

// Converting JSON object to JS object


var obj = JSON.parse(json);

// Define recursive function to print nested values


function printValues(obj) {
for(var k in obj) {
if(obj[k] instanceof Object) {
printValues(obj[k]);
} else {
document.write(obj[k] + "<br>");
};
}
};

// Printing all the values from the resulting object


printValues(obj);

document.write("<hr>");

// Printing a single value


document.write(obj["book"]["author"] + "<br>"); // Prints: J. K.
Rowling
document.write(obj["book"]["characters"][0] + "<br>"); // Prints:
Harry Potter
document.write(obj["book"]["price"]["hardcover"]); // Prints: $20.32

Encoding Data as JSON in JavaScript

Sometimes JavaScript object or value from your code need to be transferred to


the server during an Ajax communication. JavaScript provides JSON.stringify()
method for this purpose which converts a JavaScript value to a JSON string, as
shown below:

Stringify a JavaScript Object


The following example will show you how to convert a JavaScript object to JSON
string:

Example
// Sample JS object
Try this code »
var obj = {"name": "Peter", "age": 22, "country": "United States"};

// Converting JS object to JSON string


var json = JSON.stringify(obj);
alert(json);
The output of the above example will look something like this:

{"name":"Peter","age":22,"country":"United States"}

Lets now cover Advanced Examples

Given a collection that contains the detail information of employees who

are working in the organization. We need to find some values from that

nested collections of details. That collection is known as the JSON object

and the information inside object are known as nested JSON object.

Example 1: We create the nested JSON objects using JavaScript code.


Consider an example, suppose there are details of 4 employees and we
need to find the street number of the first employee then it can be done in
the following way.
employees[0].address.["street-no"]
If we need to find the residential details of the second employee then use
the following instruction.
employees[1].address.["street-no"]
Note: The dot is an operator which indicates that select the street number
from the address field of the first employee. That “street-no” is inside the
“address”, so the dot operator is used.
To print the above result in the document, we need to use document.write

<!DOCTYPE html>
<html>

<body>
<h2 style="color:green;">
GeeksForGeeks
</h2>

<script>
var employees = [
{
"emp_id":101,
"empname":"Ram",
"salary":60000,
"address" :
{
"street-no":20,
"plot-no":121,
"city":"pune",
"contact" :
{
"landline" : 2292099,
"mobile" : 8907632178
}
}
},
{
"emp_id":102,
"empname":"Shyam",
"salary":50000,
"address" :
{
"street-no":12,
"plot-no":221,
"city":"pune"
}
},
{
"emp_id":103,
"empname":"Lakhan",
"salary":40000,
"address" :
{
"street-no":11,
"plot-no":432,
"city":"pune"
}
},
{
"emp_id":104,
"empname":"Snigdha",
"salary":60000,
"address" :
{
"street-no":21,
"plot-no":222,
"city":"pune"
}
}]

document.write("<b>" + "Employee Id : "


+ "</b>" + employees[0].emp_id + "<br>");
document.write("<b>" + "Employee Name : "
+ "</b>" + employees[0].empname + "<br>");

document.write("<b>" + "Employee Salary : "


+ "</b>" + employees[0].salary + "<br>");

document.write("<b>" + "Address -> "


+ "Street Number : " + "</b>" +
employees[0].address["street-no"]);
</script>
</body>

</html>
Output:

Example 2: We need to create the nested JSON objects using JavaScript.


Consider an example that contains the information of 4 employees and we
need to find the mobile number of the first employee then it can be done
in the following manner.
employees[0].address.contact["mobile"]
To find the contact details of the second employee.
employees[1].address.contact["mobile"]
The dot operator is used for selecting the mobile from the contact field of
the address field of the second employee.

<!DOCTYPE html>
<html>

<body>
<h2 style="color: green;">
GeeksForGeeks
</h2>
<script>
var employees = [
{
"emp_id":101,
"empname":"Ram",
"salary":60000,
"address" :
{
"street-no":20,
"plot-no":121,
"city":"pune",
"contact" :
{
"landline" : 2292099,
"mobile" : 8907632178
}
}
},
{
"emp_id":102,
"empname":"Shyam",
"salary":50000,
"address" :
{
"street-no":12,
"plot-no":221,
"city":"pune"
}
},
{
"emp_id":103,
"empname":"Lakhan",
"salary":40000,
"address" :
{
"street-no":11,
"plot-no":432,
"city":"pune"
}
},
{
"emp_id":104,
"empname":"Snigdha",
"salary":60000,
"address" :
{
"street-no":21,
"plot-no":222,
"city":"pune"
}
}]
document.write("<b>" + "Employee Id : "
+ "</b>" + employees[0].emp_id + "<br>");

document.write("<b>" + "Employee Name : "


+ "</b>" + employees[0].empname + "<br>");

document.write("<b>" + "Employee Salary : "


+ "</b>" + employees[0].salary + "<br>");

document.write("<b>" + "Address -> "


+ "Street Number : " + "</b>"
+ employees[0].address["street-no"] + "<br>");

document.write("<b>" + "Address -> "


+ "Phone Number -> " + "</b>"
+ "<b>" + "Mobile : " + "</b>"
+ employees[0].address.contact["mobile"]
+ "<br>");
</script>
</body>

</html>

Output:

Example 3: We have created a JSON object that consists personal details


like their first name, last name, gender etc. using JavaScript. Suppose, our
JSON object contains details of 2 people and we need to find the first name
and last name of the second person then we need to do the following.
For first name
Person[1].Name["FirstName"]
For Last name
Person[1].Name["LastName"]

<!DOCTYPE html>
<html>

<body>
<h2 style="color: green;">
GeeksForGeeks
</h2>

<script>
var Person = [
{
"Name" : {
"FirstName" : "Smita",
"LastName" : "Verma"
},
"Degree" : {
"BE" : "CSE",
"MTECH" : "CSE"
},
"Gender" : "Female"
},
{
"Name" : {
"FirstName" : "Ramesh",
"LastName" : "Rajput"
},
"Degree" : {
"BE" : "CIVIL",
"MTECH" : "CIVIL"
},
"Gender" : "Male"
}]

document.write("<b>" + "FirstName : " + "</b>"


+ " " + Person[1].Name["FirstName"] + "<br>");

document.write("<b>" + "LastName :" + "</b>" + " "


+ Person[1].Name["LastName"] + "<br>");

document.write("<b>" + "Degree : " + "->" + "BE : "


+ "</b>" + " " + Person[1].Degree["BE"] + "<br>");

document.write("<b>" + "Gender :" + "</b>" + " "


+ Person[1].Gender + "<br>");
</script>
</body>

</html>

Output:

That is all for json guys. Hope you understand how we can play with JSON. In coming sessions you
will know how we can get data from server. Convert it and then display to users.

You might also like