Skip to main content
JavaScript Basics
CHAPTER 23 Beginner

JavaScript JSON

Updated: May 12, 2026
15 min read

# JavaScript JSON

Web applications rarely exist in isolation. The Frontend (your JavaScript running in the browser) needs to talk to the Backend (a database, a weather API, a payment gateway). But how do they talk to each other? They use JSON.

In this chapter, we will learn how to convert complex JavaScript objects into text, and vice versa, allowing data to be transmitted across the internet.

1. Introduction

JSON stands for JavaScript Object Notation. It is a lightweight text-based data interchange format.

Even though it has "JavaScript" in the name, JSON is language-independent. A Python server, a PHP database script, and a Java mobile app can all read and write JSON. It is the universal language of the modern web.

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Identify the strict syntax rules of JSON.
  • Convert JavaScript Objects into JSON strings using JSON.stringify().
  • Parse JSON strings back into JavaScript Objects using JSON.parse().
  • Avoid common JSON formatting errors.
  • Build a Product JSON Viewer mini-project.

3. JSON Syntax Rules

JSON looks almost identical to a standard JavaScript Object Literal, but it is strictly just a long text string. Because it is text, it has very rigid rules:

  1. 1. Data is in name: value pairs.
  1. 2. Data is separated by commas ,.
  1. 3. Curly braces {} hold objects.
  1. 4. Square brackets [] hold arrays.
  1. 5. CRITICAL: All keys (names) MUST be enclosed in double quotes "".
  1. 6. Values must be a String (in double quotes), Number, Object, Array, Boolean, or null. (Functions and Dates are NOT allowed).

json
1234567
// Example JSON String
{
    "firstName": "John",
    "lastName": "Doe",
    "age": 30,
    "isActive": true
}

4. JSON.stringify()

If you have data stored in a JavaScript Object, you cannot send it to a server. You must "serialize" it (turn it into a string) first.

javascript
1234
// Example JavaScript
const userObj = { name: "Alice", age: 25 };
const jsonText = JSON.stringify(userObj);
// jsonText is now '{"name":"Alice","age":25}'

5. JSON.parse()

If you receive data from a server, it will arrive as a raw text string. You cannot use data.name on a text string. You must "parse" it (turn it back into an Object).

javascript
1234
// Example JavaScript
const rawServerData = '{"name":"Alice","age":25}';
const userObj = JSON.parse(rawServerData);
// Now you can use userObj.name

---

6. Real-world Examples & Code Snippets

Example 1: Creating JSON vs JavaScript Object

Notice the subtle but strict differences.

javascript
12345678910
// Example JavaScript

// 1. JavaScript Object (No quotes on keys needed, single quotes on values allowed)
const jsObj = { 
    id: 1, 
    title: 'Hello' 
};

// 2. JSON String (Double quotes strictly required on keys and string values)
const jsonString = '{ "id": 1, "title": "Hello" }';

Example 2: Parsing JSON from a "Server"

Let's simulate receiving a weather response from a server.

javascript
123456789
// Example JavaScript
// The raw string we received
const response = '{ "city": "London", "temp": 15, "rain": false }';

// Convert to an Object
const weather = JSON.parse(response);

// Now we can interact with it
console.log(`It is currently ${weather.temp} degrees in ${weather.city}.`);

Example 3: Stringifying Data to Send to a Server

Let's simulate preparing a user's form submission to be sent to a database.

javascript
1234567891011
// Example JavaScript
const formSubmission = {
    username: "coder99",
    password: "secretpassword"
};

// Convert to string for transmission
const payload = JSON.stringify(formSubmission);

console.log(payload); 
// Output: {"username":"coder99","password":"secretpassword"}

Example 4: Dealing with Arrays in JSON

JSON natively supports arrays. You will deal with Arrays of Objects constantly.

javascript
123456
// Example JavaScript
const serverList = '[{"id":1, "name":"Apple"}, {"id":2, "name":"Banana"}]';

const fruitsArray = JSON.parse(serverList);

console.log(fruitsArray[1].name); // Output: Banana

Example 5: Formatting Output with JSON.stringify

When debugging, printing a massive JSON string in the console is unreadable. stringify has hidden parameters to make it pretty!

javascript
1234567891011121314
// Example JavaScript
const config = { theme: "dark", volume: 100, version: 1.2 };

// Parameters: (data, replacer function, number of spaces for indentation)
const prettyJson = JSON.stringify(config, null, 4);

console.log(prettyJson);
/* Output:
{
    "theme": "dark",
    "volume": 100,
    "version": 1.2
}
*/

Example 6: The Date Object Trap

JSON does not support JavaScript Date objects. If you stringify a Date, it becomes a static string. When you parse it back, it remains a string, NOT a Date object!

javascript
12345678910
// Example JavaScript
const event = { title: "Party", date: new Date() };

const jsonEvent = JSON.stringify(event);
// Looks like: {"title":"Party","date":"2024-10-18T14:30:00.000Z"}

const parsedEvent = JSON.parse(jsonEvent);

console.log(typeof parsedEvent.date); // Output: string (NOT an object!)
// parsedEvent.date.getFullYear() // ERROR!

*Fix: You must manually convert the string back to a date: new Date(parsedEvent.date).*

Example 7: The Function Trap

JSON cannot store functions. If you try to stringify an object containing a method, the method will be silently deleted.

javascript
12345678
// Example JavaScript
const person = {
    name: "John",
    sayHi: function() { console.log("Hi"); }
};

const jsonStr = JSON.stringify(person);
console.log(jsonStr); // Output: {"name":"John"} (The function vanished!)

Example 8: Handling Bad JSON

If you try to parse invalid JSON (maybe the server threw a PHP error and returned HTML instead of JSON), your entire script will crash. Always use try...catch.

javascript
123456789
// Example JavaScript
const badData = '{ "name": "John", }'; // Trailing comma is ILLEGAL in JSON

try {
    const obj = JSON.parse(badData);
    console.log("Success");
} catch (error) {
    console.log("Failed to parse JSON: " + error.message);
}

---

7. Common Mistakes for Beginners

  1. 1. Using Single Quotes: "{ 'name': 'John' }" is invalid JSON. It MUST be double quotes "{ \"name\": \"John\" }".
  1. 2. Trailing Commas: { "a": 1, "b": 2, } is invalid JSON. There cannot be a comma after the last item.
  1. 3. Trying to access properties on the string: If data is a JSON string, data.name will return undefined. You must JSON.parse(data) first.

8. Best Practices

  • Always wrap JSON.parse() inside a try...catch block when dealing with third-party APIs, as you cannot guarantee the server won't send corrupted text.
  • Use JSON.stringify(data, null, 2) when writing JSON data to console logs or log files so human developers can actually read it.

9. Mini Project: Product JSON Viewer

Let's build a tool that takes a raw JSON string from an input, parses it, and displays it in a beautiful UI.

HTML:

html
12345678910111213141516171819202122232425262728293031323334
<!-- Example HTML -->
<!DOCTYPE html>
<html>
<head>
    <style>
        /* Example CSS */
        body { font-family: Arial; padding: 20px; background: #f4f4f4;}
        textarea { width: 100%; height: 100px; font-family: monospace; padding: 10px; box-sizing: border-box;}
        button { background: #333; color: white; border: none; padding: 10px 20px; cursor: pointer; margin-top: 10px;}
        .error { color: red; font-weight: bold; margin-top: 10px; }
        .card { background: white; padding: 15px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.2); margin-top: 15px; width: 250px;}
    </style>
</head>
<body>

    <h2>JSON Parser</h2>
    <p>Simulate receiving this JSON string from a server:</p>
    
    <textarea id="jsonInput">
{
    "id": 99,
    "product": "Wireless Headphones",
    "price": 120.50,
    "inStock": true
}
    </textarea>
    <br>
    <button onclick="parseData()">Parse & Display</button>
    
    <div id="output"></div>

    <script src="jsonviewer.js"></script>
</body>
</html>

jsonviewer.js:

javascript
123456789101112131415161718192021222324252627
// Example JavaScript
function parseData() {
    const rawText = document.getElementById("jsonInput").value;
    const outputDiv = document.getElementById("output");
    
    // Always use try...catch when parsing!
    try {
        // 1. Convert text to JavaScript Object
        const dataObj = JSON.parse(rawText);
        
        // 2. Build UI
        let stockStatus = dataObj.inStock ? "In Stock" : "Sold Out";
        
        outputDiv.innerHTML = `
            <div class="card">
                <h3>${dataObj.product}</h3>
                <p><strong>Price:</strong> $${dataObj.price.toFixed(2)}</p>
                <p><strong>Status:</strong> ${stockStatus}</p>
                <p><small>ID: ${dataObj.id}</small></p>
            </div>
        `;
        
    } catch (err) {
        // If the user typed invalid JSON in the textarea
        outputDiv.innerHTML = `<p class="error">Invalid JSON: ${err.message}</p>`;
    }
}

10. Exercises

  1. 1. Create a JavaScript object let car = { make: "Toyota", model: "Corolla" };. Write code to convert this object into a JSON string and console.log() it.
  1. 2. Given the JSON string let serverRes = '{"status": 200, "message": "Success"}';, write code to parse it and console.log() the message property.
  1. 3. Find the syntax error in this JSON string: '{"name": "Alice", "age": 25, }'

11. MCQs (Multiple Choice Questions)

Q1: What does JSON stand for? A) JavaScript Ordered Network B) JavaScript Object Notation C) Java Standard Output Node D) Just Some Ordinary Numbers *Answer: B*

Q2: Which method is used to convert a JavaScript Object into a JSON string? A) JSON.parse() B) JSON.toString() C) JSON.serialize() D) JSON.stringify() *Answer: D*

Q3: Which of the following is VALID JSON? A) { name: "John" } B) { 'name': 'John' } C) { "name": "John" } D) [ "name": "John" ] *Answer: C (Keys MUST have double quotes)*

12. Interview Questions

Q: Can you store a JavaScript function inside a JSON string? *A: No. JSON is strictly a data-interchange format. It supports primitive values (Strings, Numbers, Booleans, null) and structural types (Objects, Arrays). Functions, Dates, and undefined are not allowed and will be stripped out during stringification.*

13. FAQs

Q: Are there alternatives to JSON? *A: Yes, XML was the industry standard before JSON. XML looks like HTML tags (<name>John</name>). However, JSON is much lighter, faster to parse, and native to JavaScript, which is why it completely dominated the web.*

14. Summary

  • JSON is a strict text format used to send data across the web.
  • JSON keys must be in "double quotes".
  • JSON.stringify() turns Objects into Text.
  • JSON.parse() turns Text back into Objects.
  • Always use try...catch when parsing JSON.

15. Next Chapter Recommendation

We now know how to package our data using JSON. But how do we actually send it across the internet to a real server? In the next chapter, JavaScript Fetch API and AJAX, we will learn how to make HTTP requests and bring our apps fully online.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·