Methods for converting strings to objects

Method one
JSON.parse()

let str = '{"name":"zs","age":18}'
JSON.parse(str) //{name: "zs", age: 18}

Method 2
eval()

let str = '({"name":"zs","age":18})'
//注意这字符串里面必须加上小括号否则报错,eval会执行'()'内部的代码
console.log(eval(str))

Method 3
Function(str)()

//注意这里不需要加小括号
let str = '{name:"zs",age:18}'
console.log( new Function('return' + str)() )

Summary
JSON.parse()
can only convert standard JSON strings (the key must be a string, and the string must be enclosed in double quotes)
eval(str)
converts the string into a js statement, and executes
if you do not want the conversion to be js statement, you can use parentheses to wrap the string
Function(str)()
can only convert object strings
Do not use eval if necessary, try to use Function instead
Use JSON.parse() to convert standard json strings, otherwise use function

Guess you like

Origin blog.csdn.net/weixin_44162077/article/details/130015373