Closed loglot closed 1 day ago
JSON.stringify
won't serialise functions. Since the Func
property is a function, it gets lost during serialisation and deserialisation and that's the normal behaviour.
Try this one:
// Custom decycle and retrocycle
function decycleWithFuncs(obj) {
return JSON.stringify(obj, (key, value) => {
if (typeof value === 'function') {
return value.toString();
}
return value;
});
}
function retrocycleWithFuncs(json) {
return JSON.parse(json, (key, value) => {
if (typeof value === 'string' && value.startsWith('function')) {
return eval('(' + value + ')');
}
return value;
});
}
// Assumed your Item class look like:
export class Item {
constructor(text, func) {
this.Text = text;
this.Func = func;
}
}
var list = [];
list[0] = new Item("text info", function func() {
/* required code */
});
var listBak = decycleWithFuncs(list);
list = retrocycleWithFuncs(listBak);
console.log(list);
Try this one:
when using the TS playground you linked i ran it and got
[LOG]: [{
"Text": "text info"
}]
JSON does not include functions. Your 'should' statement is incorrect.
i'm making objects like this
Item being a class that has the variables
Text
andFunc
. the log would return[{"Text":"text info"}]
when it should return[{"Text":"text info", Func: /* function info */}]