The JSON of JS

Source: Internet
Author: User
Tags tojson

first, the understanding of JSONJSON is a data format, not a programming language, and JSON does not belong to JavaScript. The syntax of JSON can represent the following three types of values1) Simple valueThe same syntax as JS, you can represent strings in JSON (you must use double quotes, single quotes cause syntax errors), numeric values, booleans, and null, but undefined is not supported. 2) Objectthe JSON object is a complex data type that represents a set of unordered key-value pairs
{    "name": "Nicholas",    "age": "+"}  
3) ArrayA list that represents a set of ordered valuesarray Representation of JSON: [+, ' Hi ', true]Note: Arrays also have no variables and semicolons4) A more complex collection of arrays and objects in combination      
[//json Array also has no variables and semicolons    {"title": "Haha"     ,"authors":        ["1": "2"        ,"3 ":" 4 "    ]}," name ":" Xixi "]        

      The difference between JSON and JavaScript object literals :  
// JavaScript Object literal var obj = {    "name": "Nicholas",    "age": +    }; // JSON Object {    "name": "Nicholas",    "age":       

1, there is no declaration variable (JSON does not have the concept of variable);2, there is no end of the semicolon;3, theJSON string must use double quotation marks (single quotation marks can cause syntax errors); second, parsing and serialization 2.1 JSON ObjectThere are two methods of JSON objects:stringify (): Serializes a JS object into a JSON stringParse (): Parse JSON string into native JavaScript value
var book = {    "Professional JavaScript",    authors: [        "Nicholas C. Zakas "    ],    3,    (); var jsontext =//  {"title": "Professional JavaScript", "authors": ["Nicholas C. Zakas "]," edition ": 3," Year ": +}

 The default json.stringify () Output JSON object does not contain any whitespace characters or reductions.

When serializing a JavaScript object, all functions and prototype objects are intentionally ignored and not reflected in the results. In addition, any property with a value of undefined will be skipped, and the result will end up with an instance property with a value of valid JSON data type.

var // Object {title: "Professional JavaScript", authors:array[1], Edition:3, year:2011}
2.2 Serialization Optionsjson.stringify () can receive three parameters, the first parameter is the JavaScript object to serialize, the second parameter is a filter, can be an array or a function; The third argument is an option that indicates whether indentation is preserved in the JSON string. when the second argument is an array, the returned result will only contain the attributes in the array;
var // {"title": "Professional JavaScript", "edition": 3}
when it is a function, the function has two parameters, the property name and the property value, according to the property name can know which attributes should be serialized, the function return value is the value of the corresponding key, if the function returns undefined, then the corresponding property is ignored.
varJsontext = json.stringify (book,function(key, value) {Switch(key) { Case"Authors":            returnValue.join (",");  Case"Year":            return5000;  Case"edition":            returnundefined; default:            returnvalue; }}); //{"title": "Professional JavaScript", "Authors": "Nicholas C. Zakas "," Year ":
The third parameter is used with the indentation and whitespace in the control result, the parameter is a numeric value, which represents the number of spaces indented at each level, the maximum indent is 10, and the parameter can be a string, such as a tab or "--", the string length cannot exceed ten;       ToJSON () method: As a supplement to a function filter, returns its own JSON data format.
var book = {    "Professional JavaScript",    authors: [        "Nicholas C. Zakas "    ],    3,    ()    ,function () {        return this. title;    }; var // "Professional JavaScript"
Suppose you pass an object into Json.stringify () and serialize the object in the following order:(1) if the Tojson () method is present and can be used to obtain a valid value, the function is called. Otherwise, the object itself is returned. (2) If the second parameter is provided, apply this function filter. The value passed into the function filter is the value returned by step (1). (3) The corresponding serialization of each value returned by step (2). (4) If a third parameter is provided, the corresponding formatting is performed. 2.3 Parsing OptionsJson.parse () can also receive a parameter, which is a function called a restore function (Reviver), and a restore function is often used when converting a date string to a data date object.
var book = {    "Professional JavaScript",    authors: [        "Nicholas C. Zakas "    ],    3,    +,    new Date (11,1  )}; var jsontext = json.stringify (book); // {"title": "Professional JavaScript", "authors": ["Nicholas C. Zakas "]," edition ": 3," Year ":," ReleaseDate ":" 2011-11-30t16:00:00.000z "}

var function (key, value) {    if(key = = "ReleaseDate")        {returnnew  Date ( value);     Else {        return  value;     // Object {title: "Professional JavaScript", authors:array[1], Edition:3, year:2011, Releasedate:thu Dec 01 2011 00: 00:00 gmt+0800 (China Standard Time)}//
Three, say a few words tojson ()

The ToJSON method is used by the json.stringify function. json.stringify serializes a JavaScript value into JSON text. " >json.stringify  to serialize JavaScript values into JSON text.  tojson method is provided to json.stringify, the tojson method was called when json.stringify was called." If the  tojson  method is provided to the  json.stringify , the  tojson  method is called when class= "input" >json.stringify .

tojson method is a built-in member of The date JavaScript object. " The >tojson  method is a built-in member of the Date javascript object.  

You can override the ToJSON method of the Date type , or you can define the ToJSON method for other object types to enable data conversion for a specific object type before JSON serialization .

varContact =NewObject (); Contact.firstname= "Jesper"; Contact.surname= "Aaberg"; Contact.phone= ["555-0100", "555-0120"];contact.tojson=function(key) {varReplacement =NewObject ();  for(varValinch  This)    {        if(typeof( This[Val]) = = = ' String ') Replacement[val]= This[Val].touppercase (); ElseReplacement[val]= This[Val]}returnreplacement;};varJsontext = json.stringify (contact);//{"FirstName": "JESPER", "surname": "Aaberg", "Phone": ["555-0100", "555-0120"]}

The JSON of JS

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.