Differences between JSON. stringify (), eval (), JSON. parse (), and evaljson. parse
JSON.stringify(value [, replacer] [, space])
Value
Required. The JavaScript value to be converted (usually an object or array ).
Replacer
Optional. The function or Array Used for the conversion result.
If replacer is a function, JSON. stringify calls this function and passes in the keys and values of each member. Use the return value instead of the original value. If this function returns undefined, the Member is excluded. The root object key is an empty string :"".
If replacer is an array, only members with key values in the array are converted. The conversion sequence of members is the same as that of keys in the array. When the value parameter is an array, the replacer array is ignored.
Space
Optional. Add indentation, spaces, and line breaks to the returned JSON text to make it easier to read.
If space is omitted, the returned text is generated without any extra space.
If space is a number, the returned text is indented at each level to specify the number of spaces. If space is greater than 10, the text is Indented by 10 spaces.
If space is a non-empty string (for example, "\ t"), the returned text is indented to characters in the string at each level.
If space is a string of more than 10 characters, the first 10 characters are used.
Returns a string containing JSON text.
JSON. stringify () and eval () are used to parse strings and convert them to json data.
Var jsonData = '{"data1": "Hello ,","Data2": "world !} ';
Var evalJson = eval ('+ jsonData + ')');
The purpose of parentheses is to force the eval function to forcibly convert the expressions in parentheses into objects when processing JavaScript code, rather than being executed as statements.
Var jsonParseJson = JSON. parse (jsonData );
In this way, strings in json format are converted into json objects.
However, there is a difference between the two.
Var value = 1;
Var jsonstr = '{"data1": "hello", "data2": ++ value }';
Var data1 = eval_r ('+ jsonstr +'); console. log (data1); // The value is 2.
Var data2 = JSON. parse (jsonstr); console. log (data2); // Error
Conclusion: when parsing a string, eval will execute the code in the string (the consequence is rather bad ),
In the above example, it is extremely insecure to change the value of the original value due to parsing a json string using eval,
Malicious users can easily inject Trojan links into json strings.
Therefore, JSON. parse () is recommended for parsing strings.
This method not only captures syntax errors in JSON, but also allows you to input a function to filter or convert the parsing results.