Initial knowledge of JSON

Source: Internet
Author: User
Tags iso 8601 tojson

Roughly Introduction

  JSON (javascript object Notation JavaScript Objects notation), JSON is a data format, not a programming language. Although it has JavaScript in its name, it does not belong to javascript, as is the case with Java and Javascript. And it's not only JavaScript that uses it, after all, JSON is just a data format. Many programming languages have parsers and serializers for JSON.

JSON was presented by Douglas Crockford in 2001, in order to replace the XML

▓▓▓▓▓▓ syntax

The syntax of JSON can contain three types of values:

Simple values

Object

Array

▓▓▓▓▓▓ Simple values

Simple values: using the same syntax as JavaScript, you can represent strings, numbers, booleans, and Null in JSON

    note:The "1" JSON does not support special values in JavaScript undefined

"2" JSON string must use double quotation marks (single quotation marks can cause syntax Errors)

         Valid JSON data         "hellow world!"         5         true         null

  

▓▓▓▓▓▓ Object

Object as a complex data type that represents an ordered set of key-value pairs in which the value in each Key-value pair can be either a simple value or a value of a complex data type

The object in JSON is slightly different from the literal in javascript:

1. No variable declared

2, no need to add a semicolon at the end

3. The property name of the object in JSON must be double-quoted at any time

    Note: There should never be two identically named properties in the same object

        Literal in javascript var person        = {            name: "Lao Wang",            age:21        };        JSON        {            "name": "Lao wang",            "age": +        /        /can be embedded in object        {            "name": "Lao wang",            " Age ": +,            " school ": {                " name ":" tjlg ",                " location ":" xiqing "            }        }

  

▓▓▓▓▓▓ Array

The JSON array takes the form of an array literal in JavaScript

        JavaScript        var values = [21, "xiqing", true];        JSON        values = [21, "xiqing", true]

▓▓▓▓▓▓json Object

The early JSON parser was basically the Eval () function using JavaScript. Because JSON is a subset of JavaScript syntax, the eval () function can parse, interpret, and return JavaScript objects and arrays, but using the Eval () function to evaluate a JSON data structure is risky, and you should be able to execute some malicious code. So use the Eval () function as little as possible

ECMAScript 5 Defines the global object JSON as a specification for parsing JSON Behavior. Browsers that support this object are IE 8+, Firefox 3.5+, Safari 4+, Chrome, and Opera 10.5+. For earlier versions of the browser, you can use a shim:https://github.com/douglascrockford/json-js.

There are two methods of JSON objects:

1, stringify ()

2. Parse ()

▓▓▓▓▓▓stringify ()

The Stringify () method serializes a JavaScript object into a JSON string

    Attention:

"1" by default, The JSON string for the json.stringify () output does not contain any space characters or indents

        var person = {            name: "Lao Wang",            grade: {                "中文版": "n",                "Math": "98"            }        };        var Jsonperson = json.stringify (person);        Console.log (jsonperson);        {"name": "Lao Wang", "grade": {"english": "", "" Math ":" 98 "}}

"2" if the member of the object is a undefined or a function, the member is ignored

If the members of the array are undefined or functions, the values are converted to NULL

        var person = {            name:function () {},            sex:undefined,            age:21,            grade: [undefined,function () {}, "中文版"] ,        }        var jsonperson = json.stringify (person);        Console.log (jsonperson);        {"age": +, "grade": [null,null, "中文版"]}

"3" json.stringify () ignores the Object's non-traversal properties

        var person = {};        Object.defineproperties (person,{            ' name ': {                value: "Lao Wang",                enumerable:true            },            ' age ': {                value:21,                enumerable:false            }        });        var Jsonperson = json.stringify (person);        Console.log (jsonperson);        {"name": "Lao Wang"}

In fact, json.stringify () can receive two additional parameters, in addition to the JavaScript object being serialized, that specify that the JavaScript object be serialized in a different way

The first parameter is a filter, which can be an array or a function

The second parameter is an option that indicates whether indentation is preserved in the JSON string

      

1. When the first parameter is an array

If the filter parameter is an array, then the result of Json.stringify () will contain only the attributes listed in the array

      Attention:

"1", Filter only valid for first layer property of object

        var person = {            name: "Lao Wang",            grade: {                "中文版": "n",                "Math": "98"            }        };        var Jsonperson = json.stringify (person,["name", "Math"]);        Console.log (jsonperson);        {"name": "Lao Wang"}

"2" Filter Invalid Array

        var values = [+, ' He ', true, ' we '];        var jsonvalues = json.stringify (values,["he"]);        Console.log (jsonvalues);        [+, "he", true, "we"]

2. When the first argument is a function

The incoming function receives two parameters, a property (key) name, and a property Value. Depending on the name of the property (key), you know how to handle the properties in the object that you want to serialize. The property name can be only a string, and the key name may be an empty string when the value is not a value of a key-value pair. To change the result of a serialized object, the value returned by the function is the value of the corresponding key.

        note: If the function returns undefined or no return value, the corresponding property is ignored

        var values = {            name: "Lao Wang",            age:21,            sex: "male"        }        var jsonvalues = json.stringify (values,functio n (key,value) {            If (key = = "sex") {                return undefined;            } else{                return value;            }        });        Console.log (jsonvalues);        {"name": "Lao Wang", "age": 21}

3, when given a third parameter

The third parameter of the Json.stringify () method is used to control the indentation and whitespace characters in the Result. If this parameter is a numeric value, it represents the number of spaces indented at each level

Attention:

"1" as long as you pass in a valid control indent parameter value, the resulting string will contain a newline character

"2" The maximum indent space is 10, and all values greater than 10 are automatically converted to 10

"3" If the indent parameter is a string rather than a numeric value, the string will be used as the indent character in the JSON string (no longer using Spaces)

        The parameter is the value        var person = {            name: "Lao Wang",            grade: {                "中文版": "n",                "Math": "98"            }        };        var Jsonperson = json.stringify (person,null,4);        Console.log (jsonperson);    /*        {"            name": "Lao Wang",            "grade": {"english                ": "", ""                Math ":" 98 "            }        }    */        //parameter is string        var person = {            name: "Lao Wang",            grade: {                "中文版": "", ""                Math ":" 98 "            }        };        var Jsonperson = json.stringify (person,null, "-_-| |");        Console.log (jsonperson);    /*            {        -_-||" Name ":" Lao Wang ",        -_-| |" Grade ": {        -_-| | -_-||" 中文版 ":",        -_-| | -_-||" Math ":" 98 "        -_-| |}        }    */

▓▓▓▓▓▓tojson ()

sometimes, json.stringify () does not satisfy the need for custom serialization of certain Objects. In these cases, you can call the Tojson () method on the object to return its own JSON data format

        var person = {            name: "Lao Wang",            grade: {                "中文版": "", ""                Math ":" 98 "            },            tojson:function () {                return "tojson method";            }        };        var Jsonperson = json.stringify (person);        Console.log (jsonperson);        "tojson method"

    

    note: If the Tojson () method returns undefined, then if the object containing it is embedded in another object, the value of the object will become Null. And if the object that contains it is a top-level object, the result is undefined

        Embedded in another object        var person = {            name: "Lao Wang",            grade: {                "中文版": "the", "                Math": "98"            },            SE X: {                value: "male",                tojson:function () {                    return undefined;}}        };        var Jsonperson = json.stringify (person,null,4);        Console.log (jsonperson);    /*        {"            name": "Lao Wang",            "grade": {"english                ": "", ""                Math ":" 98 "            }        }    */        //embed top-level object        var person = {            name: "Lao Wang",            grade: {                "中文版": "the", "                Math": "98"            },            tojson:function () {                return undefined;            }        };        var Jsonperson = json.stringify (person,null,4);        Console.log (jsonperson);        Undefined

The native Date object has a Tojson () method that automatically converts the JavaScript date object to an ISO 8601 day string (exactly as the result of calling Toisostring () on a date Object)

        var date = json.stringify (new date ("2017-1-18"));        Console.log (date);        "2017-01-17t16:00:00.000z"

    

ToJSON () can be supplemented as a function filter, so it is important to understand the internal order of Serialization. Suppose you pass an object into Json.stringify () and serialize the object in the following order

1. If there is a Tojson () method and can get a valid value through it, the method is Called. otherwise, the serialization is performed in the default order

2, If the second parameter is provided, apply this function filter. The value passed into the function filter is the value returned in the first step

3, the corresponding serialization of each value returned in the second step

4, If the third parameter is provided, the corresponding formatting is performed

▓▓▓▓▓▓json.parse ()

Json.parse () parses a JSON string into a JavaScript value

        var person = json.parse (' {' name ': ' Lao Wang '} ');        Console.log (person.name);        Lao Wang

      note: If the incoming string is not in a valid JSON format, the Json.parse method will error

The Json.parse () method can also receive another parameter, which is a function that will be called on each key-value pair. In order to distinguish between the substitution (filter) function (replacer) received by Json.stringify (), This function is called a restore function (reviver), the Restore function receives two parameters, a key and a value, and needs to return a value

      note: If the Restore function returns undefined, the corresponding key is removed from the result, and if another value is returned, the value is inserted into the result

        var person = json.parse (' {' name ': ' Lao Wang ', ' age ': +} ', function (key,value) {            if (key = = "age") {                return undefined;            } else{                return value;            }        });        Console.log (person.name);        Lao Wang

A restore function is often used when converting a date string to a data date object

        var book = {             "title": "Professional JavaScript",             "authors": ["Nicholas c. zakas"],             edition:3, year             : releasedate:new,             Date (1)         };        var jsontext = json.stringify (book,null,4);        Console.log (jsontext);    /*        {            "title": "Professional JavaScript",            "authors": [                "Nicholas C. zakas"            ],            "edition ": 3,            " Year ": +,            " releasedate ":" 2017-02-17t16:00:00.000z "        }    */        var bookcopy = Json.parse (jsontext, function (key, Value) {             if (key = = "releasedate") {                 return new Date (value);             } else{                 return value;             }        });        Console.log (bookCopy.releaseDate.getFullYear ());         2017

Initial knowledge of 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.