JSON
Intro
- This tutorial covers JSON in the context of JavaScript.
- It is recommended that you follow along with each section below. Paste or type the code into your own JavaScript, HTML, and JSON files.
- The example code for the entire tutorial series is at github.com/LearnByCheating/javascript-tutorial. There is a separate folder called json that holds the files from this tutorial. The Readme file has instructions on how to run the code both in the Node.js and Browser environments.
1. JSON Overview
- JSON stands for JavaScript object notation. It is used to store and transmit data as text in a format closely resembling JavaScript objects and arrays. So it is not actually JavaScript.
- Most APIs that transmit data over the internet use JSON syntax. NoSQL databases like MongoDB and Firebase's Firestore also use JSON syntax.
- Web storage such as cookies, sessions, and local storage can only store data as text. So JavaScript objects and arrays can be converted to JSON formatted strings before being stored.
2. JSON syntax
- JSON syntax is based on JavaScript syntax but there are some differences.
- Below is an example of a JavaScript object and array:
const jsAuthor = {
name: 'Joey R',
age: 29,
active: true,
articles: ['Learn Javascript', 'Learn NodeJS', 'Learn React'],
address: { street: '123 Main St', city: 'New York', state: 'NY', zip: '20001' },
};
const jsArticles = [
{ id: 5362, title: 'Learn JavaScript', author: 'Joey R', content: 'Lorem Ipsum' },
{ id: 5363, title: 'Learn NodeJS', author: 'Joey R', content: 'Lorem Ipsum' },
{ id: 5364, title: 'Learn React', author: 'Joey R', content: 'Lorem Ipsum' },
];
- Here is the same object and array in JSON format:
{
"name": "Joey R",
"age": 29,
"active": true,
"articles": ["Learn Javascript", "Learn NodeJS", "Learn React"],
"address": { "street": "123 Main St", "city": "New York", "state": "NY", "zip": "20001" }
}
[
{ "id": 5362, "title": "Learn JavaScript", "author": "Joey R.", "content": "Lorem Ipsum"},
{ "id": 5363, "title": "Learn NodeJS", "author": "Joey R.", "content": "Lorem Ipsum"},
{ "id": 5364, "title": "Learn React", "author": "Joey R.", "content": "Lorem Ipsum"}
]
- The most noticeable difference is that in JSON, object property names must be in quotes.
- Another difference is JavaScript you can use single or double quotes for string values, but JSON only allows double quotes.
- Third, JavaScript allows you to use trailing commas after the last object property or array element. But JSON does not allow trialing commas.
3. JSON Global Object
- There is a built-in JSON object on the global scope. But unlike String, Number, Boolean, Array, etc, the JSON object is not a constructor function, so you cannot create JSON objects, and there are no JSON instance properties or methods. The JSON global object is just a regular object with just two methods:
- JSON.stringify() to convert JavaScript into a JSON string,
- and JSON.parse() to convert a JSON string into JavaScript.
4. JSON.stringify() - Convert a JavaScript object or array into a JSON string
- Let's start with JSON.stringify.
- Pass in a JavaScript object or array as the argument, and it will return a JSON string.
- The below statements convert the jsAuthor object and the jsArticles array of objects into JSON strings.
const author = JSON.stringify(jsAuthor); const articles = JSON.stringify(jsArticles);
- The JSON string values are below.
author; // returns: "{\"name\":\"Joey R\",\"age\":29,\"active\":true,\"articles\":[\"Learn Javascript\",\"Learn NodeJS\",\"Learn React\"],\"address\":{\"street\":\"123 Main St\",\"city\":\"New York\",\"state\":\"NY\",\"zip\":\"20001\"}}"
articles; // returns: "[{\"id\":5362,\"title\":\"Learn JavaScript\",\"author\":\"Joey R\",\"content\":\"Lorem Ipsum\"},{\"id\":5363,\"title\":\"Learn NodeJS\",\"author\":\"Joey R\",\"content\":\"Lorem Ipsum\"},{\"id\":5364,\"title\":\"Learn React\",\"author\":\"Joey R\",\"content\":\"Lorem Ipsum\"}]"
- From a JavaScript perspective they are just strings. The strings are put in double quotes. All the double quotes for string and property names have to be escaped with:
\"
- Now they are ready to be stored in a database or localStorate as a string, or transmitted over the internet.
5. Convert a JSON string into JavaScript
- We just saw how to covert JavaScript to JSON, let's see how to go the other way.
- The JSON parse method converts a JSON string into JavaScript.
- Below are two strings in JSON format assigned to variables.
const jsonAuthor = `{
"name": "Sheena R",
"age": 25,
"active": true,
"articles": ["Learn HTML", "Learn SQL", "Learn Unix"],
"address": { "street": "123 Sunset Blvd", "city": "Los Angeles", "state": "CA", "zip": "90001" }
}`;
const jsonArticles = `[
{ "id": 5365, "title": "Learn HTML", "author": "Sheena R", "content": "Lorem Ipsum" },
{ "id": 5366, "title": "Learn SQL", "author": "Sheena R", "content": "Lorem Ipsum" },
{ "id": 5367, "title": "Learn Unix", "author": "Sheena R", "content": "Lorem Ipsum" }
]`;
- The JSON.parse method converts them to a JavaScript object and array:
const author = JSON.parse(jsonAuthor);
const articles = JSON.parse(jsonArticles);
6. Import a JSON file
- For the last topic we will import a JSON file into our JavaScript then display the data on a web page.
- This will display a To Do list of items from the JSON file.
- Start by creating a project folder called json.
- Open the project in a separate VS Code window so we can run Live Server on it to view the web page.
- Add three files to the project.
- The HTML file to display the web page: index.html.
- The JSON file holding our data in JSON format: todos.json
- A JavaScript file to parse the JSON data and insert it into the web page: handle-todos.js
index.html
- Create an HTML file called index.html inside the json folder. Populate it with the below:
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container">
<h1>JSON</h1>
<hr>
<h2 class="mt-3">To Do List: JavaScript topics to learn</h2>
<div class="card p-3 bg-light">
<div id="todos"></div>
</div>
<script type="module" src="handle-todos.js"></script>
</body>
</html>
- In the head element we link to the Bootstrap CDN to add Bootstrap classes to style the web page.
- There is an empty div element with an id of "todos". This is where the To Do list items will be displayed.
- At the bottom of the file is a script tag that links our HTML document to our JavaScript file. The source attribute is set to the file handle-todos.js.
- There is a type property set to module. In order to import the JSON file, the JavaScript file must be a module.
Launch the web page with Live Server:
- If you are using the VS Code text editor and have the Live Server extension installed, you can launch a local server and view the web page in your browser without any To Do list items.
- With the index.html page open, right click anywhere in the editor window. A menu will appear. Select "Open with Live Server".
- Then open your web browser to url: http://127.0.0.1:5500/index.html
- The web page should be displayed.
Todos.json
- Create a JSON file called todos.json. The file extension for JSON files is ".json".
- Populate it with an array of todo list objects with properties for id, task, due date, done, and details.
- The tasks are all related to learning JavaScript topics.
- They are in JSON syntax with the properties in quotes.
todos.json
[
{
"id": 1, "task": "JavaScript General", "due": "", "done": true, "details": "Data types, global object, built-in global objects"
},
{
"id": 2, "task": "Literals and Variables", "due": "", "done": true, "details": "Literals, primitive vs object variables, const and let vs var, scope, destructuring assignment"
},
{
"id": 3, "task": "Expressions and Operators", "due": "", "done": true, "details": "Expressions, assignment operators, arithmetic operators, comparison operators, logical operators, string operators"
}
]
handle-todos.js
- Create a JavaScript file named handle-todos.js and populate it with the below:
import fileTodos from './todos.json' assert { type: 'json' };
const elemTodos = document.getElementById('todos');
let htmlTodos = '<ul>';
fileTodos.forEach((item) => {
htmlTodos += `<li>${item.task}</li>`;
});
htmlTodos += '</ul>';
elemTodos.innerHTML = htmlTodos;
- At the top we import the todos.json file and assign it to the variable fileTodos.
- When importing a JSON file, if you add the assert statement with option { type: "json" } then the data will automatically be converted from JSON to JavaScript. That saves you from having to parse the data in a separate statement.
- Below that we get the HTML element with id "todos" from the HTML document, and assign it to variable elemTodos.
- On the next line we declare a variable called htmlTodos set to a string containing the opening HTML tag "<ul>" for an unordered list element.
- Then we iterate over the fileTodos array, inserting each array item task into an HTML list item element "<li>...</li>", and append it to the htmlTodos variable.
- After the iterator finishes going through the whole array, we append the closing unordered list tag "</ul>" to the variable.
- On the last line we assign the htmlTodos string to the innerHTML property of the elemTodos element we created above.
- We are done. Save the file, then go back to the web page in the browser. The To Do items from the JSON file should now be listed.
- And that completes this tutorial on using JSON with JavaScript.
Conclusion
The topics in this tutorial correspond with the JavaScript CheatSheet JSON category. Make sure you understand each topic so you can refer back to the CheatSheet when working on your own projects.If you have the CheatSheet desktop app and downloaded the JavaScript CheatSheet, then go through the flashcards for this category to the point where you can answer them all in order and shuffled.