JavaScript parsing JSON

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.