How to Convert JavaScript Class to JSON in JavaScript?
Last Updated :
04 Sep, 2024
When transmitting or saving class data in a structured manner, converting an instance of a class into a JSON format is also necessary. JSON (JavaScript Object Notation) supplies a method of turning objects into strings. They can be sent across a network or stored in a database, properties of the instance of the class should be taken out and changed into a format of JSON.
These are the approaches to Convert JavaScript Class to JSON in JavaScript:
Using JSON.stringify()
The simplest approach is to use JSON.stringify() which converts objects (classes) to string representation of JSON, however sensible enumeration takes place if and only if default parameters are used due to the fact that by default, it only serializes enumerable properties of a class.
Example: Below is an example demonstrating the use of JSON.stringify( ) to convert the javascript class to JSON in Javascript which converts the input into string format.
JavaScript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const person = new Person("Pankaj", 20);
const jsonString = JSON.stringify(person);
console.log(jsonString);
Output:
{"name":"Pankaj","age":20}
Custom toJSON()
Method
In case you want to have more control over the mechanism, you may define custom method toJSON() method in your class definition, this method can indicate what properties will be part of the output JSON. This approach allows you to add specific properties, exclude certain fields or even modify the values before conversation.
Example: Below is an example demonstrating use of Custom toJSON( ) Method to convert javascript class to JSON in Javascript.
JavaScript
class Car {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
toJSON() {
return {
make: this.make,
model: this.model
// you can exclude or include other properties here
};
}
}
const car = new Car("Toyota", "Corolla", 2020);
const jsonString = JSON.stringify(car);
console.log(jsonString);
Output:
{"make":"Toyota","model":"Corolla"}
Conclusion
It is possible to convert a java class instance to JSON format with the help of the JSON.stringify() function of type which is used for Object oriented programming languages since it helps to convert class members to a JSON string, if more customization is needed, implementing a custom toJSON method can target given properties in the object that are included in the conversion.