Json.parse ()

Source: Internet
Author: User

Json.parse ()

JSON is typically used to exchange data with the server.

is typically a string when receiving server data.

We can use the Json.parse () method to convert data to JavaScript objects.

Grammar
Json.parse (text[, Reviver])

Parameter description:

    • text: required, a valid JSON string.
    • reviver: Optional, a function that transforms the result, which will call this function for each member of the object.
JSON Parsing Instance

For example, we received the following data from the server:

{"Name": "Runoob", "Alexa": 10000, "site": "Www.runoob.com"}

We use the Json.parse () method to process the above data and convert it to a JavaScript object:

var obj = Json.parse (' {' name ': ' Runoob ', ' Alexa ': 10000, ' site ': ' www.runoob.com '} ');

Before parsing, make sure that your data is in the standard JSON format, otherwise it will parse an error.

You can use our online tool to detect: HTTPS://C.RUNOOB.COM/FRONT-END/53.

Once the parsing is complete, we can use the JSON data on the Web page:

<p id= "Demo" ></p> <script>var obj = Json.parse (' {"name": "Runoob", "Alexa": 10000, "Site": " Www.runoob.com "}");d Ocument.getelementbyid ("Demo"). InnerHTML = Obj.name + ":" + obj.site; </script>

Receiving JSON data from the server

We can use AJAX to request JSON data from the server and parse it into JavaScript objects.

var New  function() {    if (this this. Status = =) {         = Json.parse (this. responsetext);        document.getElementById ("Demo"). InnerHTML = myobj.name;    }}; Xmlhttp.open (true); Xmlhttp.send ();

Receiving JSON data from the service side of an array

If the JSON data for an array is received from the server, Json.parse converts it to a JavaScript array:

var New  function() {    if (this this. Status = =) {         = Json.parse (this. responsetext);        document.getElementById ("Demo"). InnerHTML = Myarr[1];}    }; Xmlhttp.open (true); Xmlhttp.send ();



Exception parsing data

JSON cannot store Date objects.

If you need to store a Date object, you need to convert it to a string.

The string is then converted to a Date object.

var text = ' {' name ': ' Runoob ', ' initdate ': ' 2013-12-14 ', ' site ': ' www.runoob.com '} '; var obj =new  Date (obj.initdate); document.getElementById ("Demo"). InnerHTML = Obj.name + "Date Created:" + obj.initdate;

We can enable json.parse for the second parameter reviver, a function that transforms the result, which each member of the object calls this function.

var text = ' {' name ': ' Runoob ', ' initdate ': ' 2013-12-14 ', ' site ': ' www.runoob.com '} '; var function (key, value) {    if (key = = "Initdate")        {returnnew  Date ( value);     Else {        return  value;}}); document.getElementById ("Demo"). InnerHTML = Obj.name + "Date Created:" + obj.initdate;

Analytic functions

JSON does not allow a function to be included, but you can store the function as a string and then convert the string to a function.

Instance
var text = ' {' "name": "Runoob", "Alexa": "function () {return 10000;}", "Site": "www.runoob.com"} '; var obj == eval ("(" + Obj.alexa + ")"); document.getElementById ("Demo"). InnerHTML = Obj.name + "Alexa rank:" + obj.alexa ();

The use of functions in JSON is not recommended.

Browser support

The Json.parse () function is supported by mainstream browsers:

    • Firefox 3.5
    • Internet Explorer 8
    • Chrome
    • Opera 10
    • Safari 4
      1. Eval (String): A function evaluates a string and executes the JavaScript code in it.

        Eval ("var a=1");     // declares a variable A and assigns a value of 1. eval ("2+3");         // performs an add operation and returns the value of the operation. eval ("mytest ()");    // executes the mytest () function. eval ("{b:2}");       // declares an object. 
      2. For a JSON string returned by the server, if the JQuery asynchronous request does not make a type description, or is accepted as a string, then an object processing is required, either in a cumbersome way or by placing the string in eval (). This is also a good way to get JSON objects in a normal Javascipt way, as illustrated below:

        var u = eval (' (' +user+ ') ');

        Why should eval be added here (' (' (' +user+ ') ')?

        The reason is that eval itself is a problem. Since JSON starts and ends in the form of {}, in JS, it is treated as a block of statements, so it must be coerced into an expression.

        The purpose of the parentheses is to force the Eval function to force the expression in parentheses to be converted to an object while processing the JavaScript code, rather than being executed as a statement (statement). For example, if the object literal {} is not enclosed, then eval will recognize the curly brace as the start and end tag of the JavaScript block, and {} will be considered an empty statement. So the following two execution results are different:

        // return undefinedalert (eval ("({})");   return Object[object]

        Test example
        var user = ' {name: ' Zhang San ', age:23, ' +       ' address:{city: ' Qingdao ', zip: ' 266071 '}, ' +    ' email: ' [email protected] ', ' +      ' showinfo:function () {' +      ' document.write ("Name:" +this.name+ "<br/>"); ' +      ' document.write ("Age: +this.age+" <br/> "); ' +      ' document.write ("Address:" +this.address.city+ "<br/>"); ' +      ' document.write ("Zip code:" +this.address.zip+ "<br/>"); ' +      ' document.write ("e-mail:" +this.email+ "<br/>");} } ';    var u = eval (' (' +user+ ') ');  U.showinfo ();

Json.parse ()

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.