Initial knowledge of JSON

Source: Internet
Author: User
Tags tojson

First, JSON is a format, text-based, better than light, for exchanging data if you have not been to the official introduction of JSON can go here, the official introduction of the first to second paragraph has been very clear about what JSON is, I will be what JSON is refined into the following aspects: 1. A data format what is a format? is to standardize your data to how to say, a chestnut, there is a person called "260", height "160cm", Weight "60kg", now you want to pass this person's information to others or something else, you have a lot of choices: Name "260", height "160cm", Weight "60kg" Name= "260" &height= "160cm" &weight= "60kg" <person><name> 260 </name>

 

  As you can see, the JSON format is stricter than the JS object, so most of the JS objects are written in a format that is not JSON-compliant. The following code is referenced from here var obj1 = {}; This is just a JS object//Can be called this: JSON-formatted JavaScript object var obj2 = {"width": +, "height": $, "name": "Rose"};//can call this: string var in JSON format str1 = ' {' width ': +, ' height ': $, ' name ': ' Rose '} ';//This JSON-formatted array is a slightly more complex form of json, var arr = [{"width": +, "height ": $," "name": "Rose"}, {"width": +, "height": $, "name": "Rose"}, {"width": +, "height": $, "name": "Rose"},];// This can be called a slightly more complex JSON-formatted string var str2= ' [' + ' {' width ': +, ' height ': $, ' name ': ' Rose '}, ' + ' {' width ': ', ' ' height ': 200, '    Name ":" Rose "}, ' + ' {" width ": +," height ": $," name ":" Rose "}, ' + ');  In addition, in addition to the common "normal" JSON format, either behaves as an object form {...}, or behaves as an array form [...], any individual 10 binary numeric, double quote string, Boolean, and Null are valid in JSON format. Here is the full JSON syntax reference 3.  An interesting place, JSON is not a subset of JS first look at the following code, you can copy to the console execution: var code = ' "\u2028\u2029"; Json.parse (code); Works fine eval (code); Fails these two characters \u2028 and \u2029 respectively represents the line delimiter and the paragraph delimiter, json.parse can parse normally, but as JS parsing will error. Three, these several JS in the JSON function, what to do in JS we are mainly exposed to two and JSON-related functions, respectively, for the JSON stringAnd JS data structure between the conversion, a call json.stringify, it is very smart, smart to you write a non-JSON-formatted JS object can help you to deal with the JSON format of the string, so you need to know what it did, lest it just smart, and then let you debug  long time; the other is called Json.parse, used to convert the JSON string to the JS data structure, it is very strict, your JSON string if the structure is not correct, there is no way to parse.  And they have more than one parameter, although we often use only one parameter.  In addition, there is a tojson function that we see less, but it affects json.stringify. 1. Convert the JS data structure into a JSON string--json.stringify function signature of this function is this: Json.stringify (value[, Replacer [, Space]]), the following will expand the use of each parameter, respectively,  And finally, some of the "smart" things that it does when serializing, pay special attention. 1.1 Basic use--only one parameter is required. This will be used to pass in a JSON-formatted JS object or array, json.stringify ({"Name": "Good Man", "Age": 18}) returns a string "{" Name ":" Good  Man "," Age ": 18}". We can see that the JS object we passed in is a JSON-formatted, double-quote, and no JSON-unacceptable property value, so what do you do to play, as in the example in the beginning?  No hurry, let's start with a simple example to illustrate the meaning of several parameters of the function, and then the problem. 1.2 The second argument can be a function or an array if the second argument is a function, then each property in the serialization process is converted and processed by this function if the second argument is an array,  Then only the attributes contained in this array will be serialized into the final JSON string if the second parameter is NULL, that is not the same as the null, but you do not want to set the second parameter, just want to set the third parameter, you can set the second parameter is NULL This second parameter is the function var friend={"firstName": "Good", "LastName": "Man", "Phone": "1234567", "Age": 18};var friendafter=      Json.stringify (Friend,function (key,value) {if (key=== "phone") return "(+value)";    else if (typeof value = = = "Number") return value + 10; else return value;  If you delete this else clause, the result will be undefined}); Console.log (Friendafter); Output: {"FirstName": "Good", "LastName": "Man", "Phone": "[1234567", "Age": 28} If the second argument is a function, then this function must have a return for each item,  This function accepts two parameters, a key name, and a property value, and the function must return the new property value for each original property value. So the question is, what if the input is not an object form of a key-value pair, but an array of square brackets? , such as the friend above: friend=["Jack", "Rose", then what is the key and value received by this property-by-attribute function?  If it is an array, then key is the index, and value is the array item, and you can print out this key and value validation in the console inside the function. This second parameter is the array var friend={"FirstName": "Good", "LastName": "Man", "Phone": "1234567", "Age": 18};//note the following array has a value that is not  Any one of the above object's property names var friendafter=json.stringify (friend,["FirstName", "Address", "phone"]); Console.log (Friendafter); {"FirstName": "Good", "Phone": "1234567"}//The specified "address" is ignored because it is not found in the original object if the second argument is an array, only the properties that appear in the array will be serialized into the result string,  A property that is not found in this provided array is not included, but the property that exists in the source JS object is ignored and does not give an error. 1.3 The third parameter is used to beautify the output--it is not recommended to use whitespace characters specified for indentation, you can take the following values: is a number of 1-10, representing a few white space characters is a string, use this string instead of a space, up to the first 10 characters of the string without providing the parameter equals set to null equals setting a number less than 1 var friend={"firstName": "Good", "LastName": "Man", "Phone": {"Home": "1234567", "Work": "7654321"}};//direct conversion is this://{"firstName": "Good", "LastName": "Man", "phone": {"Home"  : "1234567", "Work": "7654321"}}var friendafter=json.stringify (friend,null,4);  Console.log (Friendafter); /*{"FirstName": "Good", "LastName": "Man", "phone": {"Home": "1234567", "Work": "7654321"}}*/  var friendafter=json.stringify (friend,null, "hahahaha");  Console.log (Friendafter); /*{hahahaha "FirstName": "Good", Hahahaha "LastName": "Man", Hahahaha "phone": {Hahahahahahahaha "Home": "1234567", hahah  Ahahahahaha "Work": "7654321" Hahahaha}}*/var friendafter=json.stringify (Friend,null, "Whatareyoudoingnow");  Console.log (Friendafter); /* up to 10 characters {whatareyou "firstName": "Good", Whatareyou "LastName": "Man", Whatareyou "phone": {whatareyouwhatareyou " Home ":" 1234567 ", whatareyouwhatareyou" work ":" 7654321 "whatareyou}}*/lolAll right, don't do this. Serialization is for transmission, the transmission is the smaller the better, plus the inexplicable indentation, parsing difficulties (if it is a string), but also weaken the characteristics of light weight. 1.4 Note that this function is "smart" (important) if there are other uncertainties, then the best way is to "have a try", the console to do the experiment is clear. The key name is not double quotation marks (including no quotation marks or single quotation marks), will automatically become double quotation marks, the string is a single quotation mark, will automatically be double quotation marks after the last attribute has a comma, will be automatically stripped of the non-array object properties can not be guaranteed in a particular order in the serialized string in this good understanding, That is, the non-array object in the final string does not guarantee that the property order and the original consistent Boolean, number, String wrapper object is automatically converted to the corresponding original value in the serialization process, that is, your new string ("Bala") will become "Bala", new number (2017 will become 2017undefined, arbitrary function (there is actually a function that will happen magic, later say) and symbol The value (symbol is described in ES6 for symbol) appears in the property value of the non-array object: It is ignored during serialization when it appears in the array: converted to Nulljson.stringify ({x:undefined, y:function () {  return 1;}, Z:symbol ("")});  Occurs in a non-array object whose property value is ignored: "{}" json.stringify ([Undefined, object, Symbol ("")]); Appears in the property value of the array object and becomes null: "[Null,null,null]" NaN, Infinity, and-infinity, whether in an array or non-array object, are converted to null all with the symbol Properties that are property keys are completely ignored, even if the Replacer parameter is forced to specify that properties that contain their non-enumerable are ignored by 2. Parsing a JSON string into a JS data structure--json.parse function signature for this function is: Json.parse (text[, Reviver]) If the first argument, that is, the JSON string is not a valid string, then this function throws an error, So if you're writing a back-end script that returns a JSON string, it's a good idea to call the JSON string-related serialization function of the language itself, and if you're going to stitch the implemented serialization string yourself, pay particular attention to whether the serialized string is legal, Legally, this JSON string exactly conforms to the JSON requirements of strictFormat. It is important to note that there is an optional second parameter, which must be a function that will be processed and returned before the property has been parsed but not returned. var friend={"FirstName": "Good", "LastName": "Man", "phone": {"Home": "1234567", "Work": ["7654321", "999000"]}};//  We first serialize it to Var friendafter=json.stringify (friend); ' {"FirstName": "Good", "LastName": "Man", "phone": {"Home": "1234567", "Work": ["7654321", "999000"]}} '///and then parse it out,    In the function of the second parameter, the key and Valuejson.parse (Friendafter,function (k,v) {Console.log (k) are printed;    Console.log (v); Console.log ("----");}); *firstname good----lastName man----home 1234567----0 7654321----1 999000----work []----phone Object----  Object----*/Look at these outputs, you can see that the traversal is from the inside out, probably from the inside out of the word will be misunderstood, the innermost is the inner array of two values ah, but the output is from the first property, how is it from the inside out? This from the inside refers to the composite properties, in layman's terms, traversal, from beginning to end to traverse, if it is a simple attribute value (numeric, String, Boolean and null), then the direct traversal is done, if you encounter the property value is an object or array form, then pause, first traverse the sub-JSON,  The principle of traversal is the same, and when this composite property traversal is completed, then the traversal of this property is returned.  Essentially, this is a depth-first traversal. There are two points to note: If Reviver returns undefined, the current property is removed from the owning object, and if other values are returned, the returned value becomes the new property value of the current property. You can notice that the last set of outputs in the example above does not appear to have a key, in fact this key is an empty string, and the last object is the last to parse the completed objects, becauseTo the top, there is no real attribute. 3. The magical function that affects json.stringify--object.tojson if you implement the ToJSON method on a JS object, Then when calling Json.stringify to serialize the JS object, Json.stringify will serialize the value returned by the Tojson method of the object as a parameter.        var info={"msg": "I Love You", "ToJSON": function () {var replacemsg=new Object ();        replacemsg["MSG"]= "Go die";    return replacemsg; }};  Json.stringify (info);  Out of Si, the return is: ' "{" msg ":" Go die "}" ', OK, ignore the function is this function. " In fact, the date type can be passed directly to Json.stringify to do parameters, in which the reason is that the date type built-in Tojson method.

  

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.