Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Convert JavaScript Class to JSON in JavaScript?
JavaScript classes serve as blueprints for creating objects with properties and methods. When working with APIs or data storage, you often need to convert class instances to JSON format for serialization. This article demonstrates several approaches to convert JavaScript classes to JSON with practical examples.
Approaches to Convert JavaScript Class to JSON
- Using JSON.stringify() Method
- Adding a Custom toJSON() Method
- Using Object.assign() Method
- Using Custom Serializer
Using JSON.stringify() Method
JSON.stringify() is the most straightforward method to convert a class instance to JSON. It transforms the object's enumerable properties into a JSON string, automatically excluding methods.
class User {
constructor(username, age) {
this.username = username;
this.age = age;
}
}
const user = new User("PankajBind", 21);
// Convert class instance to JSON
const jsonString = JSON.stringify(user);
console.log("JSON String:", jsonString);
JSON String: {"username":"PankajBind","age":21}
Adding a Custom toJSON() Method
By default, JSON.stringify() includes all enumerable properties. You can add a custom toJSON() method to control which data gets serialized, such as excluding sensitive information.
class User {
constructor(username, age, password) {
this.username = username;
this.age = age;
this.password = password; // Sensitive data
}
toJSON() {
// Exclude sensitive data like password
return {
username: this.username,
age: this.age
};
}
}
const user = new User("PankajBind", 21, "secretPassword");
// Convert class instance to JSON
const jsonString = JSON.stringify(user);
console.log("JSON String:", jsonString);
JSON String: {"username":"PankajBind","age":21}
Using Object.assign() Method
Object.assign() creates a shallow copy of the class instance as a plain object, which can then be converted to JSON. This approach is useful when you want to ensure you're working with a plain object before serialization.
class User {
constructor(username, age) {
this.username = username;
this.age = age;
}
}
const user = new User("PankajBind", 21);
// Convert class instance to a plain object
const plainObject = Object.assign({}, user);
// Convert plain object to JSON
const jsonString = JSON.stringify(plainObject);
console.log("JSON String:", jsonString);
JSON String: {"username":"PankajBind","age":21}
Using Custom Serializer
You can pass a replacer function to JSON.stringify() to customize the serialization process. This gives you fine-grained control over which properties to include or exclude during conversion.
class User {
constructor(username, age, role) {
this.username = username;
this.age = age;
this.role = role;
}
}
const user = new User("PankajBind", 21, "admin");
// Custom replacer function to exclude 'role'
const jsonString = JSON.stringify(user, (key, value) => {
if (key === "role") {
return undefined; // Exclude this key
}
return value;
});
console.log("JSON String:", jsonString);
JSON String: {"username":"PankajBind","age":21}
Comparison of Methods
| Method | Use Case | Customization |
|---|---|---|
JSON.stringify() |
Simple serialization | None |
toJSON() method |
Control serialization per class | High |
Object.assign() |
Create plain object copy | Low |
| Custom replacer | Dynamic property filtering | High |
Conclusion
Converting JavaScript classes to JSON is essential for data serialization. Use JSON.stringify() for simple cases, implement toJSON() for class-level control, or use custom replacers for dynamic filtering based on your specific requirements.
