javascript - 如何存储/检索包含获取新数据的函数的 JSON 对象?
问题描述
const Data = {
teachers: {
size: 15,
num: 4,
color: 'blue'
}
}
const person = {
name: 'John',
group: Data.teachers, // This is Default. If I do this, the entire teachers tree gets cached. Later, teachers tree changes, this is unusable.
group: () => Data.teachers // I want to do this, so that it fetches fresh data. But, see below for the LJSON problem...
}
我了解 JSON.stringify 不支持函数。
我研究了 LJSON ( https://github.com/MaiaVictor/LJSON )。LJSON 不能解决问题。它们还按原样缓存 Data.teacher。使用 LJSON 时,如果Data.teachers
发生变化,则调用group()
不会得到最新的。它将返回老树。
(当前堆栈是 React-Native,带有 AsyncStorage,使用 JSON.stringify/parse。)
解决方案
您是否尝试过&的toString()
方法?Function
eval
const fn = (arg) => {
console.log('function:', arg)
}
fn('yes, it works')
const jsonFn = JSON.stringify(fn.toString()) // now its a JSON.stringified string
const newJsonFn = JSON.parse(jsonFn) // parsing it back from JSON to string
const newFn = eval(newJsonFn) // eval!!!
newFn('yes, it works again')
重要的
是的,这个片段解决了你的问题。但不要忘记这eval
是一个危险的工具:关于 eval 安全问题。
推荐阅读
- javascript - 用掩码替换每个逗号
- r - 创建一个虚拟变量列,指示记录是否在第二个数据框中?
- vb.net - 如何在返回文本中添加某些特定字符串的颜色
- javascript - 覆盖库中的 javascript 辅助函数
- mysql - 在 SQL 查询中准备语句,同时在 PHP 中保存 JSON 数据
- javascript - 即使 DOM 以其他方式显示,JQuery 也没有获得更新的值
- machine-learning - 用于热图类型图像的卷积神经网络
- angular - 如何解决 Angular 8 中的“safeHtml 管道不起作用”
- javascript - 根据上一个项目单击切换显示
- apache - 使用 Raspbian 和 Apache 的反向代理