How to convert javascript string to json: 1. Parse in eval mode, the code is [var json = eval('(' str ')')]; 2. New Function form; 3. Use global JSON object.
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.
How to convert javascript string to json:
1, eval method parsing, I am afraid this is the earliest parsing method. As follows:
The code is as follows:
function strToJson(str){ var json = eval('(' + str + ')'); return json; }
Remember not to forget the parentheses on both sides of str.
2, the new Function form is quite weird. The following
The code is as follows:
function strToJson(str){ var json = (new Function("return " + str))(); return json; }
3, use the global JSON object, as follows:
The code is as follows:
function strToJson(str){ return JSON.parse(str); }
Related Free learning recommendations: javascript (video)
The above is the detailed content of How to convert javascript string to json. For more information, please follow other related articles on the PHP Chinese website!