In JavaScript, we can store JavaScript functions in JSON objects, allowing us to serialize and store executable code alongside data. we will explore three approaches to store a JavaScript function in JSON.
These are the following approaches:
Table of Content
Using JSON.stringify()
In this approach, we are using JSON.stringify() to convert a JavaScript function func1 into a string representation using func1.toString(). This string representation is then stored in JSON object data with a key func1, and finally, the entire JSON object is converted into a JSON string jsonData.
Syntax:
JSON.stringify(value, replacer, space);
Example: The below example uses JSON.stringify to store a java script function in JSON.
const func1 = function() {
console.log("Hello from GFG!");
};
const data = {
func1: func1.toString()
};
const jsonData = JSON.stringify(data);
console.log(jsonData);
Output
{"func1":"function() {\n console.log(\"Hello from GFG!\");\n}"}
Using a Custom toJSON() Method
In this approach, we are defining a JavaScript function func2 and creating a JSON object data that includes func2. We also implement a custom toJSON() method within data to specify how func2 should be converted to JSON using this.func2.toString(). When JSON.stringify(data) is called, it uses the custom toJSON() method to convert func2 into a string representation and include it in the resulting JSON string jsonData.
Example: The below example uses the Custom toJSON() Method to store a JavaScript function in JSON.
const func2 = function() {
console.log("Hello from GFG!");
};
const data = {
func2,
toJSON: function() {
return {
func2: this.func2.toString()
};
}
};
const jsonData = JSON.stringify(data);
console.log(jsonData);
Output
{"func2":"function() {\n console.log(\"Hello from GFG!\");\n}"}
Using a replacer Function in JSON.stringify()
In this approach, JSON.stringify() is used with a replacer function that checks if a value is a function, converting it into a string with toString(), enabling the storage of JavaScript function func3 in JSON format with proper string representation.
Syntax:
JSON.stringify(value[, replacer[, space]])
Example: The below example uses the replacer Function in JSON.stringify() to store a JavaScript function in JSON.
const func3 = function() {
console.log("Hello from GFG!");
};
const jsonData = JSON.stringify({ func3 },
function(key, value) {
if (typeof value === 'function') {
return value.toString();
}
return value;
});
console.log(jsonData);
Output
{"func3":"function() {\n console.log(\"Hello from GFG!\");\n}"}