A deep dive into structure, usage, parsing, and real-world considerations
JSON (JavaScript Object Notation) is a lightweight, text-based format for representing structured data. It is commonly used for transmitting data between a server and a client, or storing configuration data in files.
{
"name": "Alice",
"age": 24,
"isStudent": false,
"skills": ["HTML", "CSS", "JavaScript"],
"address": { "city": "Lucknow", "country": "India" }
}
This looks similar to a JavaScript object, but remember: JSON is a string, not an object. It uses double quotes for keys and string values and cannot include methods or comments.
Letβs look at the key differences:
// JavaScript Object
const user = {
name: "Alice",
age: 24,
greet() { return "Hello"; } // β
valid in object
};
// JSON string
const jsonUser = '{"name":"Alice","age":24}'; // β οΈ only data, no functions
Converts a JavaScript object into a JSON string.
const obj = { name: "Alice", age: 24 };
const jsonStr = JSON.stringify(obj);
console.log(jsonStr);
// Output: {"name":"Alice","age":24}
Converts a JSON string back into a JavaScript object.
const jsonData = '{"name":"Alice","age":24}';
const user = JSON.parse(jsonData);
console.log(user.name); // Output: Alice
Allows filtering or transforming values during stringification.
const user = { name: "Alice", age: 24, password: "12345" };
const safeJSON = JSON.stringify(user, ["name", "age"]);
console.log(safeJSON);
// Output: {"name":"Alice","age":24}
Transforms values while parsing back into an object.
const data = '{"name":"Alice","joined":"2024-01-10"}';
const parsed = JSON.parse(data, (key, value) => {
if (key === "joined") return new Date(value);
return value;
});
console.log(parsed.joined instanceof Date); // true
undefined, Infinity, or NaN.
const data = { a: undefined, b: NaN, c: Infinity };
console.log(JSON.stringify(data));
// Output: {"b":null,"c":null}
JSON cannot handle circular structures β where an object references itself. Attempting to stringify such an object throws an error.
const obj = {};
obj.self = obj;
JSON.stringify(obj); // β TypeError: Converting circular structure to JSON
flatted or custom replacers.
Most modern APIs use JSON as their response format. For example:
fetch("https://api.example.com/user")
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error("Error:", err));
JSON.stringify() and JSON.parse() for conversion.