Home > Blockchain >  How can I give a method in JSON?
How can I give a method in JSON?

Time:03-07

How can I give a method in JSON object of local storage after storing the value, how I getItem (method/function) data from local storage and use it?

CodePudding user response:

JSON is used to serialize data objects and does not support serializing function objects or symbol values.

You could however store the name of the function in local storage, say as item "functionName", and use a dictionary of function objects in code to look up the function by name.

const funcIndex = {
    function x(argList) {
       // function x body
    },
    function y(argListY) {
       // function y body
    }
 }
 let fName = localStorage.getItem("functionName"); // previously stored
 const func = funcIndex[fName]; // function referred to by name in local storage.

CodePudding user response:

You can stringify the function itself, then upon restoring evaluate it back to life.

function foo(x) {
    console.log(x   3)
}

var str_foo = ""   foo;

var obj = {
    my_function: str_foo
}

// store it in some json
var json = JSON.stringify(obj)

// then when restoring,
var obj2 = JSON.parse(json)
var foo2 = eval("("   obj2.my_function   ")");

foo2(3)     
// console logs 6

Warning: this will not work for native methods like localStorage.getItem so I hope you didn't mean to store that.

Warning2: make sure you trust the source of the JSON because there's an evil eval there.

  • Related