Enjoying this tutorial?
Subscribe to Ram N Java for straightforward, beginner-friendly coding lessons!
Subscribe on YouTubeCan You Include Functions in JSON?
Standard JSON format does not allow functions directly. JSON is designed strictly for data storage and transmission, supporting text, numbers, booleans, arrays, and objects—not executable code.
However, situations arise where passing function-like behavior alongside data is required. JavaScript offers a reliable workaround: store the function as a string and parse it back into an active function using eval().
How Parsing Functions in JSON Works
- Write the function as a text string: In your JSON-like text structure, format the function inside quotation marks.
- Parse the text with JSON.parse(): Convert the main JSON payload into a regular JavaScript object.
- Convert the string back to a function: Use
eval()on that property to turn the string into an executable JavaScript function. - Execute the function: Call the property just like any ordinary JavaScript function to access its return value.
Practical Code Example
const text = '{"name":"Peter", "age":"function () { return 30; }"}';
const obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");
document.getElementById("output").innerHTML = obj.name + " is " + obj.age() + " years old.";
Running this in the browser yields: Peter is 30 years old. The string conversion allows JavaScript to execute the embedded code seamlessly.
No comments:
Post a Comment