Home » JSON

Introduction to JSON (JavaScript Object Notation)

JSON Introduction: In this tutorial, we are going to learn about the introduction to JSON (JavaScript Object Notation) with the sample code and examples.
Submitted by Siddhant Verma, on November 09, 2019

JSON stands for JavaScript Object Notation and is a very popular light-weight interchangeable format of data used today. Writing and reading JSON data is very convenient. It's also very easy to generate JSON data and parse it into strings, objects, etc. If you're familiar with hashmaps in C++ STL, JSON can be described as a hashmap C++ equivalent for JavaScript since it's based on key-value pairs. It is essentially a string that looks like a JavaScript object.

Sample code:

{
	"id": "0001",
	"type": "donut",
	"name": "Cake",
	"ppu": 0.55,
	"batters":
		{
			"batter":
				[
					{ "id": "1001", "type": "Regular" },
					{ "id": "1002", "type": "Chocolate" },
					{ "id": "1003", "type": "Blueberry" },
					{ "id": "1004", "type": "Devil's Food" }
				]
		},
	"topping":
		[
			{ "id": "5001", "type": "None" },
			{ "id": "5002", "type": "Glazed" },
			{ "id": "5005", "type": "Sugar" },
			{ "id": "5007", "type": "Powdered Sugar" },
			{ "id": "5006", "type": "Chocolate with Sprinkles" },
			{ "id": "5003", "type": "Chocolate" },
			{ "id": "5004", "type": "Maple" }
		]
}

Above is an example of JSON data, one can see how JSON data looks like, how it is essentially a string with key-value pairs but looks completely like a JavaScript object.

Most of the API's or servers return JSON data as a response. That response is highly nested and organized so that the frontend developer can consume it easily as per her needs.

We'll use a fake rest API available https://jsonplaceholder.typicode.com/ for seeing how to work with JSON data. Head over to the website and copy the URL https://jsonplaceholder.typicode.com/todos/. We'll make a GET request to this URL and see the JSON response we get back. You can also see various endpoints of this API at https://jsonplaceholder.typicode.com/ but here we'll be using https://jsonplaceholder.typicode.com/todos/ endpoint that returns us a load of JSON data.

Create a simple index.html file and link it to app.js,

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>JSON Data</title>
</head>

<body>
    <h1>JSON Data</h1>

    <script src="app.js"></script>
</body>

</html>

Now to go app.js and send a GET request to the URL,

var request = new XMLHttpRequest();
request.onreadystatechange = function() {
    if (request.reayState === 4 && request.status === 200) {
        document.write(request.responseText);
    } else {
        console.log('Error occurred!');
    }

}
request.open('GET', 'https://jsonplaceholder.typicode.com/todos/');
request.send();

Now run your index.html by right clicking it and selecting open with chrome or directly running the live server. You will see some congested data on the screen. This is because our JSON data is unorganised and not indented properly. If you're using chrome, install the chrome extension JSONView from here,

https://chrome.google.com/webstore/detail/jsonview/chklaanhfefbnpoihckbnefhakgolnmc?hl=en

Now run your index.html file again and click the extension icon. You can now properly see the JSON response data that we got back from the API,

[[
	{
	userId: 1,
	id: 1,
	title: "delectus aut autem",
	completed: false
	},
	{
	userId: 1,
	id: 2,
	title: "quis ut nam facilis et officia qui",
	completed: false
	},
	{
	userId: 1,
	id: 3,
	title: "fugiat veniam minus",
	completed: false
	},
	{
	userId: 1,
	id: 4,
	title: "et porro tempora",
	completed: true
	},
	{
	userId: 1,
	id: 5,
	title: "laboriosam mollitia et enim quasi adipisci quia provident illum",
	completed: false
	},
	{
	userId: 1,
	id: 6,
	title: "qui ullam ratione quibusdam voluptatem quia omnis",
	completed: false
	},
	{
	userId: 1,
	id: 7,
	title: "illo expedita consequatur quia in",
	completed: false
	},
	{
	userId: 1,
	id: 8,
	title: "quo adipisci enim quam ut ab",
	completed: true
	},
	{
	userId: 1,
	id: 9,
	title: "molestiae perspiciatis ipsa",
	completed: false
	},
	{
	userId: 1,
	id: 10,
	title: "illo est ratione doloremque quia maiores aut",
	completed: true
	},
	{
	userId: 1,
	id: 11,
	title: "vero rerum temporibus dolor",
	completed: true
	},
	{
	userId: 1,
	id: 12,
	title: "ipsa repellendus fugit nisi",
	completed: true
	},
	{
	userId: 1,
	id: 13,
	title: "et doloremque nulla",
	completed: false
	},
	{
	userId: 1,
	id: 14,
	title: "repellendus sunt dolores architecto voluptatum",
	completed: true
	},
	{
	userId: 1,
	id: 15,
	title: "ab voluptatum amet voluptas",
	completed: true
	},
	{
	userId: 1,
	id: 16,
	title: "accusamus eos facilis sint et aut voluptatem",
	completed: true
	},
	{
	userId: 3,
	id: 45,
	title: "velit soluta adipisci molestias reiciendis harum",
	completed: false
	},
...
]

It looks something like above. In the request.open() method, change the url by adding '1' at the end of the endpoint.

    request.open('GET','https://jsonplaceholder.typicode.com/todos/1');

Now we get a single item back,

    { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false }

We can convert JSON to an array of objects using JSON.parse() and convert that array back to a string using JSON.stringify(). Syntactically, everything in JSON is in quotes. It is widely used today because of its similarity and compatibility with JavaScript.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.