Careeroza
JSON
What is JSON?
JSON (JavaScript Object Notation) is the text format used to exchange data with servers and store configuration. It looks like JavaScript objects, but keys and strings must use double quotes, and functions, undefined and comments are not allowed.
JSON.stringify and JSON.parse
Example
const user = { name: "Asha", age: 21, skills: ["JS"], active: true };
const text = JSON.stringify(user);
console.log(text, typeof text);
console.log(JSON.stringify(user, null, 2)); // pretty print
const back = JSON.parse('{"course":"SQL","lessons":123}');
console.log(back.course, back.lessons + 1);Output
{"name":"Asha","age":21,"skills":["JS"],"active":true} string
{
"name": "Asha",
"age": 21,
"skills": [
"JS"
],
"active": true
}
SQL 124Invalid JSON
Example
Parsing invalid JSON throws, so wrap untrusted input in try...catch:
try {
JSON.parse("{name: 'Asha'}"); // keys and strings need double quotes
} catch (err) {
console.log("Invalid JSON:", err.name);
}Output
Invalid JSON: SyntaxError