How to store a javascript function in JSON
Usually a question like this indicates an X/Y problem: You need to do X, you think Y will help you do that, so you try to do Y, can't, and ask how to do Y. It would frequently be more useful to ask how to do X instead.
But answering the question asked: You could use replacer and reviver functions to convert the function to a string (during stringify
) and back into a function (during parse
) to store a string version of the function, but there are all sorts of issues with doing that, not least that the scope in which the function is defined may well matter to the function. (It doesn't matter to the function you've shown in the question, but I assume that's not really representative.) And converting a string from local storage into code you may run means that you are trusting that the local storage content hasn't been corrupted in a malicious way. Granted it's not likely unless the page is already vulnerable to XSS attacks, but it's an issue to keep in mind.
Here's an example, but I don't recommend it unless other options have been exhausted, not least because it uses eval
, which (like its close cousin new Function
)) can be a vector for malicious code:
// The objectvar obj = { a: 5, b: function (param) { return param; }};
// Convert to JSON using a replacer function to output// the string version of a function with /Function(// in front and )/ at the end.var json = JSON.stringify(obj, function(key, value) { if (typeof value === "function") { return "/Function(" + value.toString() + ")/"; } return value;});
// Convert to an object using a reviver function that// recognizes the /Function(...)/ value and converts it// into a function via -shudder- `eval`.var obj2 = JSON.parse(json, function(key, value) { if (typeof value === "string" && value.startsWith("/Function(") && value.endsWith(")/")) { value = value.substring(10, value.length - 2); return (0, eval)("(" + value + ")"); } return value;});document.body.innerHTML = obj2.b(42);
Is it not possible to store function as JSON key value in .json file in angular 5
See if that helps (functionKey
needs to be a string
, you would then use eval
to get result)
var obj = {
stringKey : "stringValue",
functionKey: "(function() { console.log('function called')})()"
}
var result = eval(obj.functionKey);
https://jsfiddle.net/spdr80c7/
pass function in json and execute
Here's a working example
Basically, you have to be careful with this sort of thing. If you take an extant javascript function, turn it to a string, and eval it, you might run into function redeclaration issues. If you are simply taking a function string from the server and you want to run it, you can do as I did on that jsfiddle:
Javascript
var myFunc = "function test() {alert('test');}";
$(document).ready(function() {
var data = new Object();
data.func = myFunc;
var jsonVal = $.toJSON(data);
var newObj = $.evalJSON(jsonVal);
eval(newObj.func);
test();
});
store the name of a function in a JSON file and later be able to load and call it from within a script?
Not sure if you've setup the right reference on the window object but shouldn't your code read:
timelineOptions.order = window[timelineOptions.order];
You've referenced the string value orderByID instead of the property name you used to set the object up.
Is it valid to define functions in JSON results?
No.
JSON is purely meant to be a data description language. As noted on http://www.json.org, it is a "lightweight data-interchange format." - not a programming language.
Per http://en.wikipedia.org/wiki/JSON, the "basic types" supported are:
- Number (integer, real, or floating
point) - String (double-quoted Unicode
with backslash escaping) - Boolean
(true and false) - Array (an ordered
sequence of values, comma-separated
and enclosed in square brackets) - Object (collection of key:value
pairs, comma-separated and enclosed
in curly braces) null
Store an array of functions JS JSON
JSON does not know functions,
your best guess would be storing
an array of strings and when you
want to use them pass them to a Function
object as argument.
How to fire a function from within a JSON object
Like this, but be sure your are doing your condition with ===
instead =
, and putting all your brackets.
let myTest = { "test": { "trigger": "load", "functionName": function(){if(1 === 1){console.log('hello');} else {console.log('goodbye');}} }};
myTest.test.functionName();
Passing javascript function in JSON
Thanks a lot all for your suggestions above. But I ended up using the answer from how to provide a click handler in JQCloud
I modified it a bit as per my requirement and it worked
var tag_list = new Array();
var obj = GetCustomJsonObj(strJSON);
for (var i = 0; i < obj.length; i++) {
tag_list.push({
text: obj[i].text,
weight: obj[i].weight,
//link: obj[i].link,
handlers: {
click: function () {
var zz = obj[i];
return function () {
alert("you have clicked " + zz.text);
}
}()
}
});
}
Related Topics
How to Declare a Global Variable in JavaScript
Maximum Call Stack Size Exceeded on Npm Install
Window.Onunload Is Not Working Properly in Chrome Browser. Can Any One Help Me
Understanding Ajax Cors and Security Considerations
When to Use the JavaScript Mime Type Application/JavaScript Instead of Text/Javascript
Function to Convert Timestamp to Human Date in JavaScript
How to Stop a Page from Unloading (Navigating Away) in Js
How to Stop a JavaScript for Loop
How to Check Whether <Ng-Content> Is Empty? (In Angular 2+ Till Now)
Jquery Function to Get All Unique Elements from an Array
Using Number as "Index" (JSON)
JavaScript Functions Like "Var Foo = Function Bar() ..."
Short-Polling VS Long-Polling for Real Time Web Applications
JavaScript Detect an Ajax Event