Back to JavaScript
2026-02-045 min read

JavaScript JSON

Learn JavaScript JSON step by step with clear examples and exercises.

Why This Matters

Welcome to this deep dive into JavaScript JSON! In this lesson, we'll explore why you need to master JSON, prerequisites, core concepts, a worked example, common mistakes, practice questions, and frequently asked questions. Let's get started!

Why This Matters

JSON (JavaScript Object Notation) is an essential part of web development, especially when working with data from APIs or databases. It allows for easy data exchange between a client (like a web browser) and a server, making it a cornerstone of modern web applications. JSON is also used in various contexts such as AJAX calls, storing data locally on the client-side, and even in some non-web scenarios like configuration files or data interchange between applications.

Prerequisites

To get the most out of this lesson, you should have a basic understanding of JavaScript syntax, variables, functions, and arrays. Familiarity with web development concepts such as AJAX calls and working with APIs would be beneficial but is not strictly necessary.

Core Concept

What is JSON?

JSON is a lightweight data interchange format that uses human-readable text to transmit data between a client and server or between different parts of an application. It is easy for humans to understand and easy for machines to parse and generate. JSON is built on two structures:

  1. Collection: An ordered list of values (arrays) or a grouping of key-value pairs (objects).
  2. Value: A string, number, boolean, null, array, or object.

JSON Syntax

Here's an example of a simple JSON object:

{
"name": "John Doe",
"age": 30,
"isMarried": true,
"hobbies": ["reading", "movies", "coding"],
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA"
}
}

In this example, we have an object with five properties. The name, age, and isMarried properties are simple values (string, number, boolean), while the hobbies property is an array of strings, and the address property is another object containing more key-value pairs.

JSON and JavaScript

In JavaScript, you can create JSON objects using literal notation or by parsing a string using the built-in JSON.parse() method:

// Create a JSON object using literal notation
let user = {
name: "John Doe",
age: 30,
isMarried: true,
hobbies: ["reading", "movies", "coding"],
address: {
street: "123 Main St",
city: "Anytown",
state: "CA"
}
};

// Parse a JSON string
let userData = '{"name":"Jane Smith","age":28,"isMarried":false}';
let userObj = JSON.parse(userData);

JSON and AJAX

When making AJAX calls, the data sent to and received from the server is often in JSON format. In JavaScript, you can send JSON data as a string or an object. To send an object, first convert it to a JSON string using JSON.stringify():

// Convert a JavaScript object to a JSON string
let userData = JSON.stringify(user);

// Send the JSON string as data in an AJAX call
fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: userData
})
.then(response => response.json())
.then(data => console.log(data));

Worked Example

Let's create a simple web application that fetches data from an API and displays it using JSON. We'll use the JSONPlaceholder API, which provides sample data for testing purposes.

  1. First, create a new HTML file with the following structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSON Example</title>
</head>
<body>
<h1>User Data:</h1>
<div id="userData"></div>

<script src="app.js"></script>
</body>
</html>
  1. Create a new JavaScript file called app.js. We'll fetch data from the JSONPlaceholder API and display it in our HTML:
// Fetch user data from the JSONPlaceholder API
fetch('https://jsonplaceholder.typicode.com/users/1')
.then(response => response.json())
.then(data => {
// Create a new HTML element to display the user data
let userDataDiv = document.getElementById('userData');
let userDataHTML = `<ul>`;

// Loop through the user's addresses and create an entry for each one
data.address.forEach(address => {
userDataHTML += `<li><strong>${address.street}</strong>, ${address.city}, ${address.state} ${address.zipcode}</li>`;
});

// Add the user's name, email, phone, and website to the HTML
userDataHTML += `<li><strong>Name:</strong> ${data.name}</li>`;
userDataHTML += `<li><strong>Email:</strong> ${data.email}</li>`;
userDataHTML += `<li><strong>Phone:</strong> ${data.phone}</li>`;
userDataHTML += `<li><strong>Website:</strong> <a href="${data.website}">${data.website}</a></li>`;

// Close the unordered list and append the HTML to the page
userDataHTML += '</ul>';
userDataDiv.innerHTML = userDataHTML;
});
  1. Save both files, open the HTML file in a web browser, and you should see the user data displayed on the page!

Common Mistakes

  1. Forgetting to convert JavaScript objects to JSON strings when sending AJAX requests. To fix this, use JSON.stringify() before sending the data.
  2. Incorrectly parsing JSON responses from AJAX calls. Make sure to call response.json() on the response object.
  3. Ignoring errors in AJAX calls. Always handle errors using a catch block or by checking the status property of the response.
  4. Not properly escaping JSON strings when building them dynamically. Use JSON.stringify() to ensure that all values are correctly escaped.
  5. Parsing JSON data as a string instead of an object. Always call JSON.parse() on the response to convert it to a JavaScript object.

Practice Questions

  1. Write a function that takes an array of objects and returns a new array containing only the names of each object.
  2. Create a JavaScript object representing a person with properties for name, age, occupation, and hobbies (an array). Use JSON syntax to convert this object to a string.
  3. Modify the previous example to fetch data from multiple users and display it in an HTML table.
  4. Write a function that takes two JSON objects as arguments and returns a new JSON object containing their merged properties.

FAQ

  1. What happens if I try to parse invalid JSON? If you attempt to parse invalid JSON, JSON.parse() will throw a SyntaxError. Make sure your JSON is well-formed before parsing it.
  2. Can I use JSON for local storage in the browser? Yes, JSON is often used for storing and retrieving data from the browser's local storage. You can convert JavaScript objects to JSON strings using JSON.stringify() and parse them back to objects with JSON.parse().
  3. Is there a limit to the size of JSON data I can send in an AJAX request? The maximum size of a single HTTP request is limited by the server, browser, and network configurations. In practice, you may encounter limits as low as 10KB or as high as several megabytes.
  4. How do I escape special characters in JSON strings? JSON automatically escapes certain characters like double quotes (") and backslashes (\) when they appear within a string. To include other special characters, use the \ character followed by the character you want to escape. For example, \n represents a newline character.
  5. Can I use JSON for binary data? No, JSON is designed for transmitting text-based data. If you need to send binary data, consider using Base64 encoding or another format like Protocol Buffers (protobuf).
JavaScript JSON | JavaScript | XQA Learn