0
点赞
收藏
分享

微信扫一扫

实现 JSON.parse

本文已整理到 Github,地址 👉 ​​blog​​。


我希望我的内容可以帮助你。现在我专注于前端领域,但我也将分享我在有限的时间内看到和感受到的东西。

之前在 ​​JavaScript Eval​​​ 中有提到过,在没有 ​​JSON.parse​​​ 方法之前,我们使用 ​​eval​​ 来对 JSON 字符串进行反序列化。

偶然间发现了一篇 ​​JSON.parse 三种实现方式​​​,其中讨论了几种实现 ​​JSON.parse​​ 的方法。

其中讨论区提到了一种使用 ​​new Function​​ 实现的方法,如下:

const json = '{"name":"O.O", "age":18}'
const obj = new Function('return ' + json)() // {name: 'O.O', age: 18}

这种实现方式很简便,但需要注意的是,如果网站开启了 CSP(内容安全策略),将会报错:

Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src github.githubassets.com".

举报

相关推荐

0 条评论