JSON: Parsing and Stringification
JSON (JavaScript Object Notation) is a lightweight data format used for data exchange. Understanding JSON is essential for working with APIs and data storage.
What is JSON?
JSON is a text format for representing structured data:
{
"name": "Alice",
"age": 30,
"email": "[email protected]",
"active": true,
"hobbies": ["reading", "gaming"],
"address": {
"street": "123 Main St",
"city": "New York"
}
}
JSON.stringify()
Convert JavaScript objects to JSON strings:
const person = {
name: "Alice",
age: 30,
email: "[email protected]"
};
const json = JSON.stringify(person);
console.log(json);
// {"name":"Alice","age":30,"email":"[email protected]"}
Formatting Output
const person = {
name: "Alice",
age: 30,
email: "[email protected]"
};
// Pretty print with 2-space indentation
const json = JSON.stringify(person, null, 2);
console.log(json);
// {
// "name": "Alice",
// "age": 30,
// "email": "[email protected]"
// }
Replacer Function
const person = {
name: "Alice",
age: 30,
password: "secret123"
};
// Exclude password field
const json = JSON.stringify(person, (key, value) => {
if (key === "password") {
return undefined;
}
return value;
});
console.log(json);
// {"name":"Alice","age":30}
Replacer Array
const person = {
name: "Alice",
age: 30,
email: "[email protected]",
password: "secret"
};
// Only include name and email
const json = JSON.stringify(person, ["name", "email"]);
console.log(json);
// {"name":"Alice","email":"[email protected]"}
JSON.parse()
Convert JSON strings to JavaScript objects:
const json = '{"name":"Alice","age":30,"email":"[email protected]"}';
const person = JSON.parse(json);
console.log(person.name); // "Alice"
console.log(person.age); // 30
Reviver Function
const json = '{"name":"Alice","birthDate":"1990-01-15"}';
const person = JSON.parse(json, (key, value) => {
if (key === "birthDate") {
return new Date(value);
}
return value;
});
console.log(person.birthDate instanceof Date); // true
Practical Examples
Storing Objects in LocalStorage
// Save object
const user = { id: 1, name: "Alice", email: "[email protected]" };
localStorage.setItem("user", JSON.stringify(user));
// Retrieve object
const savedUser = JSON.parse(localStorage.getItem("user"));
console.log(savedUser.name); // "Alice"
API Communication
// Sending data
const data = { name: "Alice", email: "[email protected]" };
const response = await fetch("/api/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
});
// Receiving data
const result = await response.json();
console.log(result);
Deep Cloning Objects
const original = {
name: "Alice",
hobbies: ["reading", "gaming"],
address: { city: "New York" }
};
// Deep clone using JSON
const clone = JSON.parse(JSON.stringify(original));
// Modify clone
clone.hobbies.push("coding");
clone.address.city = "Boston";
console.log(original.hobbies); // ["reading", "gaming"]
console.log(original.address.city); // "New York"
Serializing Complex Objects
class User {
constructor(name, email) {
this.name = name;
this.email = email;
this.createdAt = new Date();
}
toJSON() {
return {
name: this.name,
email: this.email,
createdAt: this.createdAt.toISOString()
};
}
}
const user = new User("Alice", "[email protected]");
const json = JSON.stringify(user);
console.log(json);
// {"name":"Alice","email":"[email protected]","createdAt":"2025-12-18T..."}
Deserializing Complex Objects
class User {
constructor(name, email, createdAt) {
this.name = name;
this.email = email;
this.createdAt = new Date(createdAt);
}
static fromJSON(json) {
const data = JSON.parse(json);
return new User(data.name, data.email, data.createdAt);
}
}
const json = '{"name":"Alice","email":"[email protected]","createdAt":"2025-12-18T..."}';
const user = User.fromJSON(json);
console.log(user instanceof User); // true
console.log(user.createdAt instanceof Date); // true
Filtering Sensitive Data
const user = {
id: 1,
name: "Alice",
email: "[email protected]",
password: "secret123",
apiKey: "key123"
};
const sensitiveFields = ["password", "apiKey"];
const json = JSON.stringify(user, (key, value) => {
if (sensitiveFields.includes(key)) {
return undefined;
}
return value;
});
console.log(json);
// {"id":1,"name":"Alice","email":"[email protected]"}
Validating JSON
function isValidJSON(str) {
try {
JSON.parse(str);
return true;
} catch (error) {
return false;
}
}
console.log(isValidJSON('{"name":"Alice"}')); // true
console.log(isValidJSON("invalid json")); // false
Comparing Objects
function deepEqual(obj1, obj2) {
return JSON.stringify(obj1) === JSON.stringify(obj2);
}
const user1 = { name: "Alice", age: 30 };
const user2 = { name: "Alice", age: 30 };
const user3 = { name: "Bob", age: 25 };
console.log(deepEqual(user1, user2)); // true
console.log(deepEqual(user1, user3)); // false
Merging Objects
const defaults = {
theme: "light",
language: "en",
notifications: true
};
const userSettings = {
theme: "dark",
language: "es"
};
// Merge using JSON
const merged = JSON.parse(JSON.stringify({
...defaults,
...userSettings
}));
console.log(merged);
// { theme: "dark", language: "es", notifications: true }
Common Issues
Circular References
const obj = { name: "Alice" };
obj.self = obj; // Circular reference
// This will throw an error
// JSON.stringify(obj);
// Solution: use replacer function
const json = JSON.stringify(obj, (key, value) => {
if (key === "self") {
return undefined;
}
return value;
});
Undefined Values
const obj = {
name: "Alice",
age: undefined,
email: "[email protected]"
};
const json = JSON.stringify(obj);
console.log(json);
// {"name":"Alice","email":"[email protected]"}
// Note: age is omitted
Functions and Symbols
const obj = {
name: "Alice",
greet: function() { return "Hello"; },
id: Symbol("id")
};
const json = JSON.stringify(obj);
console.log(json);
// {"name":"Alice"}
// Note: functions and symbols are omitted
Performance Tips
Avoid Deep Cloning with JSON
// Slow - uses JSON serialization
const clone1 = JSON.parse(JSON.stringify(obj));
// Faster - use spread operator for shallow copy
const clone2 = { ...obj };
// Faster - use Object.assign for shallow copy
const clone3 = Object.assign({}, obj);
Cache Stringified Data
class Cache {
constructor() {
this.cache = new Map();
}
set(key, value) {
this.cache.set(key, JSON.stringify(value));
}
get(key) {
const json = this.cache.get(key);
return json ? JSON.parse(json) : null;
}
}
Summary
- JSON.stringify(): convert object to JSON string
- JSON.parse(): convert JSON string to object
- Replacer: filter properties during stringification
- Reviver: transform properties during parsing
- toJSON(): custom serialization method
- LocalStorage: store objects as JSON
- API: send/receive JSON data
- Deep clone: use JSON for deep copying
- Best practice: validate JSON before parsing
Comments