JavaScript JSON
# 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.
Data is in
name: valuepairs.
-
2.
Data is separated by commas
,.
-
3.
Curly braces
{}hold objects.
-
4.
Square brackets
[]hold arrays.
-
5.
CRITICAL: All keys (names) MUST be enclosed in double quotes
"".
-
6.
Values must be a String (in double quotes), Number, Object, Array, Boolean, or
null. (Functions and Dates are NOT allowed).
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.
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).
---
6. Real-world Examples & Code Snippets
Example 1: Creating JSON vs JavaScript Object
Notice the subtle but strict differences.
Example 2: Parsing JSON from a "Server"
Let's simulate receiving a weather response from a server.
Example 3: Stringifying Data to Send to a Server
Let's simulate preparing a user's form submission to be sent to a database.
Example 4: Dealing with Arrays in JSON
JSON natively supports arrays. You will deal with Arrays of Objects constantly.
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!
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!
*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.
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.
---
7. Common Mistakes for Beginners
-
1.
Using Single Quotes:
"{ 'name': 'John' }"is invalid JSON. It MUST be double quotes"{ \"name\": \"John\" }".
-
2.
Trailing Commas:
{ "a": 1, "b": 2, }is invalid JSON. There cannot be a comma after the last item.
-
3.
Trying to access properties on the string: If
datais a JSON string,data.namewill returnundefined. You mustJSON.parse(data)first.
8. Best Practices
-
Always wrap
JSON.parse()inside atry...catchblock 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:
jsonviewer.js:
10. Exercises
-
1.
Create a JavaScript object
let car = { make: "Toyota", model: "Corolla" };. Write code to convert this object into a JSON string andconsole.log()it.
-
2.
Given the JSON string
let serverRes = '{"status": 200, "message": "Success"}';, write code to parse it andconsole.log()the message property.
-
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...catchwhen parsing JSON.