Introduction to JSON
JSON stands for JavaScript Object Notation. It is a text format for storing and transporting data across various programming languages.
In this article, we'll be focusing on the use of JSON in JavaScript. It can be widely used for:
Storing Data.
Configuring and Verification of Data.
Generating data structures from user inputs.
Data transfer from server to server, client to server and vice-versa.
Syntax and Structure
JSON files are typically saved as .json file extensions and consist of a series of key/value pairs.
{ "key": "value" }
In this case, both the key and value are wrapped in double quotes. If this was a JavaScript Object literal - we wouldn’t need the quotes around the key, just the string value. To parse this as valid JSON, we need to remember to keep our keys in quotes and also follow some specific data types as given below:
Data Types
The following data types can be used with JSON:
Strings (in double quotes)
Numbers
Objects
Arrays
Booleans (true or false)
null
Each of the data types that are passed into JSON as values will maintain their syntax, strings will be in double quotes, but numbers will not be.
Use cases
Let's take a look at an example JSON file, profile.json :
{
"name" : "Mrinmoy",
"age" : 22,
"address" : {
"street" : "46 Graham Road",
"city" : "Kolkata"
},
"interests" : ["cricket", "biking"]
}
Here we have a name set as a string, age as a number, the address as an embedded object and the interests are an array of strings.
When you're working with JSON, you might also encounter JSON as an object or a string within the context of a program. If your JSON object is in a '.js' or '.html' file -- it'll likely be set to a variable. Then our example would look like this:
let profile = {
name: "Mrinmoy",
age: 22,
address: {
street: "46, Graham Road",
city: "Kolkata"
},
interests: ["cricket", "biking"]
}
or if stored as a string, it'll be a one-liner:
let profile = { "name":"Mrinmoy", "age":22, "address":{ "street":"46, Graham Road", "city": "Kolkata"}, "interests":["cricket", "biking"]}
Writing in the JSON format on multiple lines makes it much more readable, especially when dealing with a lot of data. JSON ignores whitespace between its elements, so you're free to space out your key-value pairs to make the data easier for reading.
Working with JSON in JavaScript
Let's understand with the help of an example. Open your text editor and create an HTML file as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSON Workings</title>
</head>
<body>
<script>
let profile = {
name: "Mrinmoy",
age: 22,
address: {
street: "46 Graham Road",
city: "Kolkata"
},
interests: ["cricket", "biking"]
}
</script>
</body>
</html>
We can access our JSON data through the console using dot notation, like this:
profile.name // Mrinmoy
profile.age // 22
profile.address.street // 46, Graham Road
profile.address.city // Kolkata
profile.interests[0] // cricket
profile.interests[1] // biking
If we want to transfer or store our data, it's very useful to be able to convert our JSON object to a string using JSON.stringify()
. And likewise, convert from a string back into an object using JSON.parse()
.
JSON.stringify()
The JSON.stringify()
function converts a JavaScript object into a JSON string. Strings are lightweight and therefore very useful when transporting data from a client to a server.
Let's get back to our previous example and assign the JSON.stringify()
method to variable s
. We pass our contacts
object into the function.
let profile = {
name: "Mrinmoy",
age: 22,
address: {
street: "46, Graham Road",
city: "Kolkata"
},
interests: ["cricket", "biking"]
}
let p = JSON.stringify(profile);
If we now take a look at s
in the console, we’ll see the JSON available to us as a string rather than an object.
'{"name":"Mrinmoy","age":22,"address":{"street":"46, Graham Road","city":"Kolkata"},"interests":["cricket","biking"]}'
The JSON.stringify()
function lets us convert objects to strings. To do the opposite, we use the JSON.parse()
function.
JSON.parse()
To convert a string back into a function we use the built-in JSON.parse()
function, to decode the string.
let profile = JSON.parse(s);
We can now access the data like a regular JavaScript object.
profile.name // Mrinmoy
Looping through arrays
It's often necessary to loop through arrays of objects when working with JSON. Let's create an array:
let user = [
{
name: "Mrinmoy",
age : 22
},
{
name : "Ishan",
age: 24
},
{
name : "Adin",
age : "21"
}
];
And let's create a for loop, to iterate through our data:
for (var a = 0; a < user.length; a++){
console.log(user[a].name);
}
----------------------------
Output:
Mrinmoy
Ishan
Adin
Accessing JSON from a URL
Most of the time we’ll need to access JSON from a URL. To do this there is an extra step involved — we will use AJAX to make a GET request for the file. For our demo, let’s take the above JSON string and put it into a new file named user.json
. It should look like this:
[
{
"name": "Mrinmoy",
"age": 22
},
{
"name": "Ishan",
"age": 24
},
{
"name": "Adin",
"age": 21
}
]
Note: As this is a JSON file (not an object), you must double-quote your keys!
Now we’ll make an XMLHttpRequest()
.
let request = new XMLHttpRequest();
We’ll open the file users.json
via GET (URL) request.
request.open('GET', 'user.json', true);
Obviously, if our JSON file is stored externally we would replace ‘user.json’
with the complete URL address e.g. ‘
https://api.myjson.com/demo/sample.json’
Now we parse our JSON data within the onload
function. And then loop through the data, displaying our ul
element.
request.onload = function () { // Convert JSON data to an object
let users = JSON.parse(this.response); let output = '';
for (var i = 0; i < users.length; i++) {
output += '<li>' + users[i].name + ' is ' + users[i].age + ' years old.'; '</li>'
}
document.getElementById('users').innerHTML = output;
}
Then finally, we submit the request!
request.send();
Here’s the final code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSON Demo</title>
</head>
<body>
<ul id="user"></ul>
<script>
let request = new XMLHttpRequest();
request.open('GET', 'user.json', true);
request.onload = function () {
// Convert JSON data to an object
let user = JSON.parse(this.response); let output = '';
for (var i = 0; i < user.length; i++) {
output += '<li>' + user[i].name + ' is ' + user[i].age + ' years old.'; '</li>'
}
document.getElementById('user').innerHTML = output;
} request.send();
</script>
</body>
</html>
We’re almost done!
But if you open up the HTML file now you’ll get a console error. As we’re calling user.json
from the file system instead of an actual domain (it's a browser security protocol). So to test this out locally, we’ll need to run it on a local server.
If you have xampp installed, go ahead and upload it to your webroot. However, a simpler solution would be to install live server via npm.
Make sure you have NodeJS installed and run npm install -g live-server
from the directory where your HTML file is stored.
After the module installation completes you simply run live-server
from the same directory and it’ll open up the HTML file on a local server.
And our data will print as specified!
Timothy is 22 years old.
Ishan is 24 years old.
Adin is 21 years old.
Using Fetch
The Fetch API is a new built-in feature of JavaScript that makes working with requests and responses much easier. We can use Fetch with our data like so:
fetch('./user.json').then(response => {
return response.json();
}).then(data => {
// Work with your JSON data here..
console.log(data);
}).catch(err => {
// What do when the request fails
console.log('The request failed!');
});
Using jQuery
If you’re using jQuery on your project, you can retrieve data using the getJSON()
function.
$(document).ready(function () {
$.getJSON('user.json', function (data) {
// Work with your JSON data here..
console.log(data[0].name);
});
});
Don’t forget to add jQuery above this function, if you’re testing it out!
Conclusion
I hope you find this article useful and has helped you increase your understanding of JSON as well as ways to use it. You'll now be able to create a JSON file and work with it using native JavaScript, Fetch API and jQuery to access data. It is widely adopted within the industry and is also a fundamental skill for all developers.
Thanks for reading 😃
I would ❤ to connect with you on Twitter | LinkedIn | GitHub Let me know in the comment section if you have any doubts or feedback.