Reference: segmentfault.com/a/119000001…

Juejin. Cn/post / 684490…

JSONS. Parse (text [reviver])

Parse the JSON string to construct JavaScript values or objects described by the string.

Reviver function optional, perform transformation operations on the object;

Method 1: eval

function myJsonParse(opt) {
    return eval('(' + opt + ') ')
}
console.log(myJsonParse(JSON.stringify({ x: 5 })))
console.log(myJsonParse(JSON.stringify([1, 'false'.false])))
console.log(myJsonParse(JSON.stringify({ b: undefined })))Copy the code



Avoid using eval unnecessarily; it is a dangerous function that executes code in executor rights. If the string code used to run eval() is maliciously modified, it could result in malicious code being run on the user’s computer under the permission of your web page/extension.

It executes JS code and has XSS vulnerabilities.

Using this method, you need to validate the JSON parameter

var rx_one = /^[\],:{}\s]*$/; var rx_two = /\\(? : ["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
var rx_three = /"[^"\\\n\r]*"|true|false|null|-? \d+(? :\.\d*)? (? :[eE][+\-]? \d+)? /g; var rx_four = /(? (: : ^ | |,)? :\s*\[)+/g;if (
    rx_one.test(
        json
            .replace(rx_two, "@")
            .replace(rx_three, "]")
            .replace(rx_four, "")
    )
) {
    var obj = eval("(" +json + ")");
}Copy the code

Method 2: Function

Function has the same string argument property as eval.

var func = new Function(arg1,arg2,… ,functionBody);

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

Eval and Function are both useful for dynamically compiling JS code, but are not recommended for practical programming.