JavaScript Notes
Master JSON in JavaScript: JSON.parse(), JSON.stringify(), working with fetch API, handling errors, nested structures, custom replacers/revivers, and real-world patterns.
Introduction
JSON (JavaScript Object Notation) is a lightweight, text-based data format used to exchange data between servers and web applications. It's the universal language of web APIs — nearly every REST API sends and receives data as JSON.
Despite its name "JavaScript Object Notation," JSON is language-independent and is used in Python, Java, PHP, Go, and virtually every other language. In JavaScript, we use two key methods: JSON.stringify() to convert objects to JSON strings, and JSON.parse() to convert JSON strings back to objects.
JSON Syntax and Data Types
JSON has strict rules — it looks similar to JavaScript objects but is NOT the same:
Valid JSON Examples
JSON.parse() — String to JavaScript Object
JSON.parse() converts a JSON string into a JavaScript value (object, array, number, etc.).
Alice 30 reading object string
Parsing Arrays
[1, 2, 3, 'hello', true, null] hello 6
Parsing Nested Structures
success Bob JavaScript developer admin 1
JSON.stringify() — JavaScript Object to String
JSON.stringify() converts a JavaScript value into a JSON string.
{"name":"Alice","age":30,"hobbies":["reading","coding"],"isActive":true}
stringPretty Printing with Indentation
{
"name": "Alice",
"age": 30,
"hobbies": [
"reading"
]
}
{
"name": "Alice",
"age": 30,
"hobbies": [
"reading"
]
}
{
"name": "Alice",
"age": 30,
"hobbies": [
"reading"
]
}What Gets Lost in JSON.stringify()
{
"name": "Alice",
"age": 30,
"score": null,
"active": true,
"tags": ["js","css"],
"badNum": null,
"inf": null
}Notice: greet, id, and sym are completely missing! NaN and Infinity become null.
JSON with Fetch API
This is the most common real-world use of JSON in JavaScript:
Leanne Graham | Sincere@april.biz | Gwenborough Ervin Howell | Shanna@melissa.tv | Wisokyburgh ... Created user ID: 11
Error Handling — Parsing Invalid JSON
// JSON.parse() throws a SyntaxError for invalid JSON
function safeJSONParse(jsonString, fallback = null) {
try {
return JSON.parse(jsonString);
} catch (error) {
console.error("Invalid JSON:", error.message);
return fallback;
}
}
// Valid JSON
console.log(safeJSONParse('{"name": "Alice"}')); // { name: 'Alice' }
// Invalid JSON (single quotes)
console.log(safeJSONParse("{'name': 'Alice'}")); // null (fallback)
// Invalid JSON (trailing comma)
console.log(safeJSONParse('{"name": "Alice",}')); // null (fallback)
// Invalid JSON (undefined)
console.log(safeJSONParse("undefined")); // null (fallback)
// Empty string
console.log(safeJSONParse("")); // null (fallback){ name: 'Alice' }
Invalid JSON: Expected property name or '}' in JSON at position 1
null
Invalid JSON: Expected double-quoted property name in JSON at position 16
null
Invalid JSON: "undefined" is not valid JSON
null
Invalid JSON: Unexpected end of JSON input
nullThe replacer Parameter — Filtering Properties
{
"name": "Alice",
"email": "alice@example.com",
"age": 30
}
{
"name": "ALICE",
"email": "ALICE@EXAMPLE.COM",
"age": 30
}The reviver Parameter — Transforming on Parse
Alice true 1995 number 52.5
JSON as a Deep Clone Tool (Limited!)
Mumbai
Delhi
["coding", "reading"]
{ date: "2026-06-12T00:00:00.000Z" }For complex objects with Dates, Maps, Sets, use structuredClone() instead:
Common Mistakes ⚠️
Mistake 1: Using Single Quotes in JSON
// ❌ INVALID JSON — single quotes not allowed
const badJson = "{'name': 'Alice'}";
JSON.parse(badJson); // SyntaxError!
// ✅ VALID JSON — must use double quotes
const goodJson = '{"name": "Alice"}';
JSON.parse(goodJson); // ✅ { name: 'Alice' }Mistake 2: Expecting Functions to Survive stringify
{"name":"Alice"}
undefinedMistake 3: Not Handling JSON.parse Errors
// ❌ Will crash if response is not valid JSON
const data = JSON.parse(apiResponseText);
// ✅ Always wrap in try/catch
try {
const data = JSON.parse(apiResponseText);
} catch (error) {
console.error("Invalid JSON from server:", error.message);
}Mistake 4: Stringifying Circular References
// ❌ Circular references throw TypeError
const obj = {};
obj.self = obj; // Circular!
JSON.stringify(obj); // TypeError: Converting circular structure to JSON
// ✅ Use a library or manual replacer for circular structuresInterview Questions 🎯
Q1. What is JSON and why is it used?
JSON (JavaScript Object Notation) is a lightweight, text-based data interchange format. It's used to exchange data between a server and a client because it's human-readable, language-independent, and easy to parse. Virtually all web APIs use JSON for data transfer.
Q2. What is the difference between JSON.parse() and JSON.stringify()?
JSON.parse(string)converts a JSON string → JavaScript value (deserialization).JSON.stringify(value)converts a JavaScript value → JSON string (serialization). You parse incoming data (from an API), and stringify outgoing data (to send to an API).
Q3. What happens when you JSON.stringify() an object with a function?
Functions are completely omitted from the JSON output. JSON doesn't support functions as a data type. If the entire value being stringified is a function,JSON.stringify()returnsundefined(not a string).
Q4. What are the JSON data types?
JSON supports: string (in double quotes), number, boolean (true/false),null, array (ordered list), and object (key-value pairs). It does NOT supportundefined, functions,Date,Symbol,NaN,Infinity, orMap/Set.
Q5. How do you handle errors when parsing JSON?
WrapJSON.parse()in atry/catchblock. It throws aSyntaxErrorif the input is invalid JSON. Common causes: single quotes instead of double, trailing commas,undefinedvalues, unquoted keys.
Q6. Can JSON be used as a deep clone method? What are the limitations?
JSON.parse(JSON.stringify(obj))works as a quick deep clone for simple objects with strings, numbers, booleans, arrays, and plain objects. Limitations: functions are lost,Dateobjects become strings,undefinedvalues are omitted,Map/Setbecome{}, circular references throw an error. UsestructuredClone()for proper deep cloning.
Q7. What does the third parameter of JSON.stringify() do?
It controls indentation for pretty-printing. Pass a number (spaces) or string (e.g.,"\t"for tabs). For example,JSON.stringify(obj, null, 2)produces nicely indented JSON with 2-space indentation.
Key Takeaways 📌
JSON.parse()converts string → object (parsing/deserialization)JSON.stringify()converts object → string (serialization)- JSON only supports: strings (double-quotes only!), numbers, booleans, null, arrays, objects
- Functions,
undefined,Symbol,Date,NaN,Infinityare lost or converted in JSON - Always use
try/catcharoundJSON.parse()— invalid JSON throwsSyntaxError fetch().then(r => r.json())isfetch()+ automaticJSON.parse()under the hood- Use
JSON.stringify(obj, null, 2)for human-readable pretty printing - JSON deep clone (
JSON.parse(JSON.stringify(obj))) works only for simple data
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JSON in JavaScript - Complete Guide: Parse, Stringify, Fetch & Error Handling.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, asynchronous, json, json in javascript - complete guide: parse, stringify, fetch & error handling
Related JavaScript Master Course Topics