Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript模拟实现JSON.parse #12

Open
GGXXMM opened this issue Aug 7, 2019 · 0 comments
Open

JavaScript模拟实现JSON.parse #12

GGXXMM opened this issue Aug 7, 2019 · 0 comments
Labels
⭐️ js js knowledge

Comments

@GGXXMM
Copy link
Owner

GGXXMM commented Aug 7, 2019

语法

JSON.parse(text[, reviver])
  • text:
    必需, 一个有效的 JSON 字符串。
  • reviver:
    可选,一个转换结果的函数, 将为对象的每个成员调用此函数。

JSON.parse功能

用来解析JSON字符串,构造由字符串描述的JavaScript值或对象。

模拟JSON.parse解析JSON字符串的功能

第一种:直接调用eval

function jsonParse(opt) {
return eval('(' + opt + ')');
}
jsonParse('{"x":5}');// { x: 5}
jsonParse('[1,"false",false]');// [1, "false", false]
直接调用eval函数,容易出现xss漏洞,不建议直接使用这个方法。
如果想用eval方法实现,可以先对参数做json格式校验,符合格式,才能调用eval。

第二种:使用new Function

var jsonStr = '{ "age": 20, "name": "jack" }';
var json = (new Function('return ' + jsonStr))();

eval和Function的区别

共同点:

Function与eval都可以将字符串转换成js代码

不同点:

  • Function创建出来的是函数,并不会直接调用,只有当手动去调用创建函数时才执行。
  • eval把字符串转成代码之后,直接就执行了。
@GGXXMM GGXXMM added the ⭐️ js js knowledge label Dec 7, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
⭐️ js js knowledge
Projects
None yet
Development

No branches or pull requests

1 participant