user1269015
user1269015

Reputation:

Store an array of functions JS JSON

So to begin with I create an array of functions using some test (like this : "alert("Hello")") and convert that text into an anonymous function using the Function(text) method. e.g.

someArray[0] = Function('alert("Hello")');

I can then run this function like so:

someArray[0]();

This works fine, however I need to be able store this array in local storage previously I have been using JSOn.Stringify to store the array however it seems that once I store the array and retrieve it from storage I can no longer run the function.

My question is how do I store the array of functions so that I can retrieve them and run them later?

Upvotes: 0

Views: 2579

Answers (2)

TDave00
TDave00

Reputation: 374

You could base64 encode the function as a string. Save it in a json file. Load the json file into your page/app. base64 decode.

Then eval() to register your new function.

//load json data from file
var jsonData = {};

//Create string representation of function
var s = "function " + atob(jsonData.func);

//"Register" the function
eval(s);

//Call the function
//'test' is the name of the function in jsonData.func
test();

OR

//load json data from file
var jsonData = {};

//create function from base64 decode
var fn = Function(atob(jsonData.func));

//test
fn();

**Of course the function would need to be formatted differently for each of those examples.

Is there a way to create a function from a string with javascript?

Upvotes: 0

user3152069
user3152069

Reputation: 416

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.

Upvotes: 2

Related Questions