Background data is often sent back to the foreground in JSON data format, parsing of course the preferred JSON object.
JSON objects have two methods that use Json.parse (str) to parse a JSON string into an object in JS.
var o = Json.parse (' {' name ': ' Zjz ', ' age ': ' + '} '); Console.log (o); // Object {name: "ZJZ", Age: " All"}
This method can also receive the second parameter, which is a function with the argument being the key of the converted object and the corresponding value.
function (key, value) { + ': ' + value ')}); // NAME:ZJZ //
Relative to parse is the stringify function, which serializes a JS object into a JSON string.
var obj = {name: ' Zjz ', Age: ' + '}; var json = json.stringify (obj); // "{" "Name": "Zjz", "age": "%"} "
But the JSON object IE8 before the browser is not supported.
The second method is through Eval.
Eval (' (' + ' {' name ': ' Zjz ', ' age ': ' + '} ' + ') '); // Object {name: "ZJZ", Age: " All"}
It is important to note that when parsing a string, parentheses are added outside the string to make it an expression, and then eval is evaluated.
Eval parsing the note points in JSON this article is quite detailed.
It is not recommended that you use Eval.
The third method uses function.
var New Function (' return ' + ' {' name ': ' Zjz ', ' age ': ' + '} ') (); // Object {name: "ZJZ", Age: " All"}
So in parsing JSON, you can use parse first, if you don't support using function again.
Try { catch(e) { try { return (new Function (' return ' + str) (); Catch (e) { alert (' JSON error ');} }
The output in this article is the output from the developer tools under Chrome.
JavaScript parsing JSON