The Wayback Machine - https://web.archive.org/web/20240906212156/https://www.geeksforgeeks.org/how-to-convert-javascript-class-to-json-in-javascript/
Open In App

How to Convert JavaScript Class to JSON in JavaScript?

Last Updated : 04 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.



Previous Article
Next Article

Similar Reads

Why does Vite create multiple TypeScript config files: tsconfig.json, tsconfig.app.json and tsconfig.node.json?
In Vite TypeScript projects you may have noticed three typescript configuration files, tsconfig.json, tsconfig.app.json, and tsconfig.node.json. Each file is used for a different purpose and understanding their use cases can help you manage TypeScript configurations for your project. In this article, you will learn about the three TypeScript config
6 min read
Convert JSON String to Array of JSON Objects in JavaScript
Given a JSON string, the task is to convert it into an array of JSON objects in JavaScript. This array will contain the values derived from the JSON string using JavaScript. There are two approaches to solving this problem, which are discussed below: Table of Content Using JSON.parse() MethodUsing JavaScript eval() MethodUsing Function ConstructorU
4 min read
How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?
JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip
2 min read
JSON Modify an Array Value of a JSON Object
The arrays in JSON (JavaScript Object Notation) are similar to arrays in JavaScript. Arrays in JSON can have values of the following types: nullbooleannumberstringarrayobject The arrays in JavaScript can have all these but it can also have other valid JavaScript expressions which are not allowed in JSON. The array value of a JSON object can be modi
2 min read
How to transforms JSON object to pretty-printed JSON using Angular Pipe ?
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will see How to use pipe to transform a JSON object to pretty-printed JSON using Angular Pipe. It meaning that it will take a JSON object string and return it pretty-p
3 min read
Difference between package.json and package-lock.json files
In this article, we will learn the major differences between package.json and package.lock.json and their needs in Node. In Node, package.json is a versioning file used to install multiple packages in your project. As you initialize your node application, you will see three files installed in your app that is node_modules, package.json, and package
3 min read
How to Write Postman Test to Compare the Response JSON against another JSON?
In the era of API-driven development, testing the API responses to ensure their correctness is of paramount importance. One such test includes comparing the JSON response of an API against a predefined JSON. In this article, we will delve into how to write a Postman test for this purpose. Table of Content What is Postman?JSON and its Role in APIsWh
4 min read
How to use cURL to Get JSON Data and Decode JSON Data in PHP ?
In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP. cURL: It stands for Client URL.It is a command line tool for sending and getting files using URL syntax.cURL allows communicating with other servers using HTTP, FTP, Telnet, and more.Approach: We are going to fetch JSON data from one of free website,
2 min read
JavaScript | Convert an array to JSON
Here is a need to convert an array into a JSON_Object. To do so we are going to use a few of the most preferred techniques. First, we need to know a few methods. 1) Object.assign() method This method copies the values of all properties owned by enumerables from source objects(one or more) to a target object. Syntax: Object.assign(target, ...sources
2 min read
How to convert JSON results into a date using JavaScript ?
The task is to convert a JSON result to JavaScript Date with the help of JavaScript. There are two methods which are discussed below: Approach 1: Use substr() method to get the integer part of the string.Use the parseInt() method followed by Date() to get the JavaScript date. Example: This example implements the above approach. C/C++ Code <h1 st
2 min read
How to Convert CSV to JSON file and vice-versa in JavaScript ?
CSV files are a common file format used to store data in a table-like manner. They can be particularly useful when a user intends to download structured information in a way that they can easily open and read on their local machine. CSV files are ideal for this because of their portability and universality. In this article, we will explain how to c
3 min read
How to Convert Excel to JSON in JavaScript ?
Converting Excel spreadsheets to JSON format is a common requirement in various applications. JavaScript code utilizes the read-excel-file library to parse the Excel data, convert it to JSON format, and display it. Additionally, it provides functionality to download the generated JSON file. ApproachCreate an HTML file with a div containing an input
3 min read
How to Convert JSON to base64 in JavaScript ?
Base 64 is the encoding scheme that represents binary data in a printable ASCII format, commonly used for data serialization and transmission. Table of Content Using btoa functionUsing Manual ConversionUsing btoa functionIn this approach, we're using btoa to encode a UTF-8 string representation of a JSON object. First, the JSON data is converted to
2 min read
How to Convert CSV to JSON in JavaScript ?
In this article, we will explain different ways to change Comma-Separated Values (CSV) data into JavaScript Object Notation (JSON) format, step-by-step. We'll break down each method with clear explanations and examples. There are several approaches available in JavaScript to convert CSV to JSON in JavaScript which are as follows: Table of Content S
3 min read
How to Convert HTML to JSON in JavaScript ?
Converting HTML to JSON is important for structured data extraction and integration with JavaScript applications. Here, we will learn different approaches to converting HTML to JSON in JavaScript. Below are the approaches to convert html to JSON in JavaScript: Table of Content Using html-to-json LibraryUsing DOM ParserUsing html-to-json LibraryIn t
2 min read
How to Convert HTML Form Field Values to JSON Object using JavaScript?
Storing HTML input data into JSON format using JavaScript can be useful in various web development scenarios such as form submissions, data processing, and AJAX requests. Here we will explore how to convert the HTML form input data into the JSON format using JavaScript. ApproachThe HTML file contains a form with input fields for name, email, and me
2 min read
How to Convert XML to JSON in JavaScript ?
Converting XML to JSON in JavaScript is crucial for simplifying data manipulation and compatibility across various systems. Here, we'll learn two methods to achieve this conversion efficiently. Below are the approaches to convert XML to JSON in JavaScript: Table of Content Using xml-js LibraryUsing DOM ParserUsing xml-js LibraryIn this approach, we
2 min read
How to Convert JSON to Blob in JavaScript ?
This article explores how to convert a JavaScript Object Notation (JSON) object into a Blob object in JavaScript. Blobs represent raw data, similar to files, and can be useful for various tasks like downloading or processing JSON data. What is JSON and Blob?JSON (JavaScript Object Notation): A lightweight format for storing and transmitting data. I
2 min read
How to Convert Map to JSON in JavaScript ?
In JavaScript, when working with data, you might encounter situations where you need to convert a Map object into a JSON format. This can be useful for sending data over the network, storing data in local storage, or interfacing with APIs that expect JSON data. Converting a Map to JSON means converting each key-value pair from the Map into a JSON o
3 min read
How to Convert JSON Object to CSV in JavaScript ?
JSON (JavaScript Object Notation) and CSV (Comma-Separated Values) are two widely used formats, each with its own strengths and applications. Fortunately, JavaScript provides powerful tools to facilitate the conversion process between these formats. These are the following approaches: Table of Content Using String ManipulationUsing csvjson library
3 min read
How to Convert String to JSON in JavaScript?
In JavaScript, converting a string to JSON is important for handling data interchangeably between server and client, parsing external API responses, and storing structured data in applications. Below are the approaches to converting string to JSON in JavaScript: Table of Content Using JSON.parse()Using eval()Using Function ConstructorUsing JSON.par
2 min read
How to Convert Blob Data to JSON in JavaScript ?
When dealing with Blob data in JavaScript, such as binary data or files, we may need to convert it into JSON format for doing so JavaScript provides us with various methods as listed below. Table of Content Using FileReader APIUsing TextDecoder APIUsing FileReader APIIn this approach, we first use the readAsText() method to read the Blob as text an
2 min read
Convert XML to JSON using JavaScript
Convert XML to JSON effortlessly using JavaScript, enabling seamless integration and manipulation of XML data within your applications. JavaScript libraries like xml-js and xmldom Library simplify the conversion process, ensuring compatibility and efficiency. Below are the approaches to convert XML to JSON in JavaScript: Table of Content Using xml-
2 min read
How to convert JSON data to a html table using JavaScript/jQuery ?
Given an HTML document containing JSON data and the task is to convert JSON data into an HTML table.  These are the following approaches for converting the JSON data to an HTML table: Table of Content Using for loopUsing JSON.stringify() methodApproach 1: Using for loopTake the JSON Object in a variable.Call a function that first adds the column na
4 min read
JavaScript Program to Convert Byte Array to JSON
In this article, we are going to learn about the conversion of a Byte Array into JSON. Converting a byte array to JSON means transforming a sequence of bytes into a structured JSON format, often involving decoding bytes to a text string and then parsing it into JSON data. Example: Input : [71, 101, 101, 107, 115, 102, 111, 114, 71, 101, 101, 107, 1
3 min read
How to Convert JSON to string in JavaScript ?
In this article, we are going to learn the conversion of JSON to string in JavaScript. Converting JSON to a string in JavaScript means serializing a JavaScript object or data structure represented in JSON format into a textual JSON string for data storage or transmission. Several methods can be used to Convert JSON to string in JavaScript, which ar
3 min read
How to Convert a Map to JSON String in JavaScript ?
A Map is a collection of key-value pairs, where each key is unique. In this article, we will see how to convert a Map to a JSON (JavaScript Object Notation) string in JavaScript. However, JSON.stringify() does not directly support Map objects. Table of Content Using Object.fromEntries() MethodUsing Array Spread and ReduceHandling Nested MapsUsing A
2 min read
How to Convert JS Object to JSON String in JQuery/Javascript?
Converting a JavaScript object to a JSON string means using the JSON.stringify() method to transform the object into a JSON-formatted string. This allows for efficient data storage, transmission, and debugging by representing complex data structures in a standardized text format. To Convert JS Object to JSON String in JQuery/Javascript we can use t
4 min read
How to Convert JSON to ArrayBuffer in JavaScript?
An ArrayBuffer is a complex data type, and structures which has a fixed length and takes binary content as the whole. Any variable that contains pure binary data will be defined in JavaScript as Simple Data, however on some occasions it is sometimes necessary to convert JSON data to an ArrayBuffer, for example when the objective is to manipulate im
4 min read
Article Tags :