Understanding of JSON

Source: Internet
Author: User

Introduction to JSON 1. JSON is what JSON, the full name is JavaScript object Notation, that is, JavaScript objects tagging method.  json is a lightweight (light-weight), text-based (text-based), readable (human-readable) format.  json has JavaScript in its name, but this means that its syntax rules refer to JavaScript objects, not only to JavaScript languages.  json is very easy to read and write for both people and machines, and the file is smaller than XML (another common data interchange format), so it quickly becomes a popular interchange format on the Web.   In recent years JavaScript has become the de facto standard language on browsers, and JavaScript is popular, and it is closely related to the popularity of JSON.   Because JSON itself is defined as a rule of reference JavaScript objects, its syntax is almost identical to the syntax of a JavaScript definition object. The founder of the  json format claims that this format is never upgraded, which means that the format has a long period of stability, files written 10 years ago can be used after 10 years, without any compatibility issues.  2. The JSON syntax rules are very simple, can be called "elegant Perfect", summed up with:-Arrays (array) is expressed in square brackets ("[]"). -Objects (object) are represented by curly braces ("{}"). -Name/value pairs (Name/value) combine the array and the object. -The name is placed in double quotation marks, and the value is a string, numeric, Boolean, null, object, and array. -Parallel data is separated by commas (","). {"Name": "Geoff Lui", "Age": 26} 3. JSON and Xmljson are often compared to XML, since the birth of JSON is more or less meant to replace XML. The advantages of Xml,json are as follows:  -has no end tag, shorter length, faster read and write-able to be parsed directly by the JAVASCRIPT interpreter-you can use the array  json:{"name": "Geoff Lui", "Age": 26, " Friends ": [" Lily "," Lucy "," Gwen "]} xml:<root><name>geoff Lui</name><age>26</age><friends>lily</friends><friends >lucy</friends><friends>gwen</friends></root> 4. JSON parsing and generation in JavaScript, there are two methods associated with this: Json.parse and json.stringify. <script>var str = ' {' name ': ' Geoff Lui ', ' age ': ' + '; var obj = Json.parse (str); The JSON string is converted to object Console.log (obj), var jsonstr = json.stringify (obj); Convert object type data to JSON-formatted data console.log (JSONSTR);</script>   text online validation that conforms to JSON syntax rules: Json.cnjson syntax rules are simple, No matter what method is summed up only a few, it refers to the C language family of some habits, learning will not feel strange.  1. Object objects are enclosed in curly braces ("{}"), and are a series of "name/value pairs" in curly braces.   Two pairs of data separated by commas (","), note two points:-Use the English comma (","), do not use the Chinese comma (",")-The Last "name/value pair" and then do not add a comma  2. An array array represents a series of ordered values enclosed in square brackets ("[]"), separated by commas.  3. The name/value pair (Name/value) name is a string that is enclosed in double quotation marks, cannot be in single quotes, and cannot have no quotation marks, which is different from JavaScript. There are only seven types of   values: string, numeric (number), objects (object), array (arrays), true, false, null. You cannot have types other than this, such as undefined, functions, and so on. The rules for   strings (string) are as follows:-double quotes in English, not single quotes, or No. -double quotation marks cannot appear in a string alone (") and right slash (" \ "). -If you want to double quote or right slash, you need to use "right slash + character" in the form of "\" and \ \, as well as other escape characters.   json string conversion to Object resolution: refers to the process of converting a string that conforms to a JSON grammar rule into an object.   Different programming languages provide a way to parse JSON strings, and here are the main explanations for the parsing methods in JavaScript. There are three main types:-use eval ()-use Json.parse ()-use third-party libraries, such as  1 such as JQuery. The eval () eval () function is a string whose function is to execute the JavaScript code directly within it. Eval () is able to parse the JSON string. It can also be seen from here that JSON and JavaScript are highly chimeric.   However, it is very rare to use eval () directly to parse it, and if your browser version is really old, this method may be needed. In addition, Eval () is a relatively dangerous function and is not recommended because the string may contain unknown elements. Here, as a study, still need to know that this is also a method.   Note that the parameters of the eval () are bracketed on both sides of the string, which is required, or an error will be added.   Because the JSON string is surrounded by curly braces ("{}"), putting it directly into eval () is executed as a block of statements, so enclose the parentheses around it so that it becomes an expression. <script>var str = "Console.log (' hello ')"; eval (str); console output Hello; because strings are executed, it is dangerous for unknown strings, so it is not recommended. </script><script>var str = ' {' name ': ' Geoff Lui ', ' Age ': 26} '; The JSON string cannot use single quotes, but the JS variable can be var obj = eval ("(" +str + ")"), Console.log (obj), console output Object {name: "Geoff Lui", age:26};//" ("+str +") "parentheses are used to pass him as a value. Otherwise str will be executed as a block of code. </script> 2. Json.parse () Most browsers now support Json.parse (), which is the recommended partyExpression JSON string converted to object   error if you enter a string that does not conform to the specification.  json.parse () can have a second parameter, which is a function. This function has two parameters: Name and value, respectively, representing names and values. When a JSON string is passed in, each set of JSON name/value pairs calls this function. The function has a return value, and the return value is assigned to the current name. <script>var str = ' {' name ': ' Geoff Lui ', ' age ': ' + '; var obj = parse (str); Console.log (obj); console output Object {name: "G Eoff Lui ", age:26};</script>  use the second parameter, you can parse the JSON string while processing some of the data. <script>var str = ' {' name ': ' Geoff Lui ', ' age ': ' + '; var obj = Json.parse (str, fun); function fun (name, value) {if (NA me = = "Age") value = 14;return value;} The Console.log (obj);</script>  object is converted to JSON string serialization, which refers to the process of translating JavaScript values into JSON strings.  json.stringify () is able to convert JavaScript values into JSON strings. The string generated by Json.stringify () can then be reverted to JavaScript values using Json.parse ().  1. The meaning of the parameter is json.stringify (value[, replacer[, Space]) value: Required parameter. The transformed JavaScript value, typically an object or an array.  replacer: Can be omitted. There are two options: a function or an array. -If it is a function, then each set of name/value pairs calls this function, which returns a value that is transformed into the result string as a name, and is ignored if undefined is returned. -If it is an array, only the names that exist in the array can be converted, and the order of the conversions is consistent with the values in the array.  space: Can be omitted. This is for typesetting, easy to read and exist. Can be inAdd blank or tab characters to the JSON string.  2. Value usage <script>var obj = {a:1,b:2,c:3,d:4};console.log (obj); var jsonstr = json.stringify (obj); Console.log (JSON STR); </script> 3. Usage of replacer <script>var obj = {a:1,b:2,c:3,d:4};console.log (obj), var jsonstr = json.stringify (obj, ["C", "A", "B"] , "\ t"); Console.log (JSONSTR); </script>  json and XML Transformations note: You can encapsulate and call a function to do the work. 1. Download the relevant file jquery.com, json.cn JSON component-jquery-jquery.json2xml.js-jquery.xml2json.js 2. The XML string is converted to a JSON object $.xml2json (str);  3. JSON object converted to XML string $.json2xml (obj);  <script src= "Jquery-2.1.4.min.js" ></script><script src= " Jquery.xml2json.js "></script><script src=" Jquery.json2xml.js "></script><script>var str = "<root>" + "<name>geoff lui</name>" + "<age>26</age>" + "<friends>alice</ Friends> "+" <friends>Gwen</friends> "+" </root> "; Console.log (str); var obj = $.xml2json (str); Console.log (obj); var jsoNstr = json.stringify (obj); Console.log (jsonstr); var person = {Name: "Geoff Lui", Age:26,mother: {name: "Lucy", Age:54},a: function () {return 1;},b:null,c:undefined};var xmlstr = $.json2xml (person); Console.log (XMLSTR);</script> The   ajax and Jsonjson files are placed on the server side, and the client requests the file with the most Ajax, enabling asynchronous requests.  1. Ajax is what the full name asynchronous JavaScript and XML, ie "Asynchronous JavaScript and XML", is generally written in Ajax. Ajax can exchange small amounts of data with the server to asynchronously update portions of a Web page. asynchronous, which means that when Ajax performs an operation to exchange data, other operations can still be performed. One of the most common applications is: open Baidu or Google home, when you enter text, the search bar below will show a few suggested search terms. This is the application of Ajax.  2. Creating and using Ajax to create Ajax objects to consider the browser version of the problem, mainly divided into two major categories: ie7+/chrome/firefox/... and IE6/IE5. function Createxhr () {if (window. XMLHttpRequest) {//To browser ie7+, Firefox, Chrome, Opera, Safarireturn new XMLHttpRequest ();} else{//to Browser IE6, Ie5return new ActiveXObject ("Microsoft.XMLHTTP");}} Then, just create it as follows. var xmlhttp;xmlhttp = CREATEXHR ();  server side has a file Test.json, request and output. Xmlhttp.open ("GET", "Test.json", true); Xmlhttp.send (); xmlhttp.onreadystatechange = function () {if ( Xmlhttp.readystate = = 4 && xmlhttp.stATUs = = $) {var jsonstr = Xmlhttp.responsetext;console.log (JSONSTR);}} Wherein, Xmlhttp.readystate has a state of XMLHttpRequest, there are five values: 0: Request uninitialized 1: Server connection established 2: Request received 3: Request processing in 4: request completed, and response ready   The value of Xmlhttp.status is the request result, 200 means "OK", and 404 means the page is not found.   Gets the response from the server, using the ResponseText or Responsexml property of the XMLHttpRequest object, which is in the form of a string, which is in XML form.   geojson and Topojsongeojson and Topojson are two data formats that conform to the JSON syntax rules for representing geographic information.  1. Geojsongeojson is the data format used to describe geospatial information. GeoJSON is not a new format, its syntax specification is in JSON format, but its name is standardized and specifically used to represent geographic information. The outermost layer of the  geojson is a single object. This object can be represented as:-Geometry (Geometry). -Feature (Feature). -Feature set (Featurecollection).   The outermost GeoJSON may contain many sub-objects, and each GeoJSON object has a type attribute that represents the type of the object, and the value of type must be one of the following. -point: Dot. -MultiPoint: Multi-point. -LineString: Line. -multilinestring: Multi-line. -Polygon: Noodles. -Multipolygon: Multi-faceted. -GeometryCollection: The collection of geometry. -Feature: Features. -featurecollection: Feature set.   Here are a few examples.   object: {"type": "Point", "coordinates": [ -105,]}  Line object: {"type": "LineString", "coordinates": [[-105, 39], [- 107,]]}  Polygon object: {"type": "Polygon", "coordinates": [[[0], [0], [5], [5], [0],]]}  by the above format can be found, each object has a member variable coordinates. If the value of type is one of point, MultiPoint, LineString, multilinestring, Polygon, Multipolygon, the object must have a variable coordinates.   If the value of type is GeometryCollection (the Geometry collection), then the object must have a variable geometries, whose value is an array, and each item of the array is a GeoJSON geometric object. For example: {"type": "GeometryCollection", "geometries": [{"Type": "Point", "coordinates": [40]},{"type": "LineString", " Coordinates ": [[[[]] [[[]]]}]}  If the value of type is Feature (characteristic), then this feature object must contain a variable geometry, representing the geometry, and the value of geometry must be a geometry object. This feature object also contains a properties that represents an attribute, and the value of properties can be any JSON object or null. For example: {"type": "Feature", "Properties": {"name": "Beijing"}, "geometry": {"type": "Point", "coordinates": [116.3671875, 39.977120098439634]}}  If the value of type is Featurecollection (a feature collection), the object must have a member named features. The value of features is an array, and each item of the array is a feature object.  2. Topojson GeoJSON's simplified version, so the file is much smaller (GeoJSON can be converted to Topojson) Topojson is GeoJSON by the topological encoding of the expanded form, by the D3 author Mike Bostock developed. Compared to the way GeoJSON uses geometry such as Polygon, point directly to represent graphics,Each geometry in the Topojson is formed by consolidating the shared edges (known as arcs).  topojson eliminates redundancy and reduces file size by 80% because the boundary line is recorded only once (for example, Guangxi and Guangdong border lines are recorded only once). Geographic coordinates use integers and do not use floating-point numbers.  3. Online tool generation geojson:http://geojson.io/simplifies, transforms GeoJSON and topojson:http://mapshaper.org/        

Understanding 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.