JavaScript JSON

JavaScript JSON

When making an Ajax request to the server, you can retrieve data from the server response in two different ways: one is using the XMLHttpRequest object The responseXML attribute accesses data in XML format; one is the responseText attribute of the XMLHttpRequest object that accesses data in string format. Currently, XML is the standard language for data transfer, but one of the disadvantages of using XML is that it is difficult to parse it and extract the data to be added to the page.
JSON (JavaScript Object Notation) is a lightweight data exchange format, which we call JavaScript Object Notation. One of the advantages of using JSON for data transfer is that JSON is actually JavaScript. It is a text format based on the JavaScript object literal syntax subset of ECMAScript version 3. This means that you can use responseText to retrieve JSON data from the server, and then use JavaScript's eval() method to convert the JSON string into a JavaScript object. Then, using additional JavaScript, you can easily extract the data from the object without processing. DOM.
In addition, there are JSON libraries for most programming languages ​​(including C++, C#, ColdFusion, Java, Perl, PHP and Python). These libraries can convert data formatted in the above languages ​​into JSON format.

Although there is a lot of publicity about how XML has cross-platform and cross-language advantages, however, unless it is applied to Web Services, in ordinary Web applications, development often shows off its brains for XML parsing, whether it is a server Whether the client generates or processes XML, or the client uses JavaScript to parse XML, often leads to complex code and extremely low development efficiency. In fact, for most Web applications, there is no need for complex XML to transmit data. The extensibility of XML rarely has advantages. Many Ajax applications even directly return HTML fragments to build dynamic Web pages. Compared with returning XML and parsing it, returning HTML fragments greatly reduces the complexity of the system, but it also lacks a certain degree of flexibility. XML uses elements, attributes, entities, and other structures. JSON is not a document format, so it does not require these additional structures. Because JSON data only includes name-value pairs (objects) or values ​​(arrays), JSON data takes up less space and executes faster than equivalent XML data.
      (1) JSON syntax
                                                                                                          using   using JSON        . In different languages, it is understood as an object, record, structure, dictionary, hash table, keyed list, or associative array. An object starts with "{" (left bracket) and ends with "}" (right bracket). Each "name" is followed by a ":" (colon); "name/value" pairs are separated by a "," (comma).
Array - an ordered list of values. In most languages, it is understood as an array. An array starts with "[" (left bracket) and ends with "]" (right bracket). Values ​​are separated by "," (comma).
JSON has no variables or other control structures. JSON is only used for data transfer.
JSON syntax is based on the JavaScript syntax of opposite literals and array literals. When using literals, the data itself is included, but the expression that generated the data is not included.
1. Data type
JSON data structure includes the following data types: characters, numbers, Boolean values ​​(true/false), null, objects, and arrays.
JSON strings must be enclosed in double quotes. They use standard JavaScript escape sequences. Therefore, add a backslash in front of the following characters:
JSON has the following forms: "(quotation marks), b (space), n (new line), f (form feed), r (carriage return) , t (horizontal positioning), u (add 4 digits to Unicode characters), \ (backslash symbol), / (forward slash symbol)
2. Object literal
.JSON uses literals to represent objects. If there is more than one member object, it can be represented in JSON as an object containing an array of two objects. The following code displays the member object in JOSN text form:

   {“memeber”:[
            {
                  “name”:”Tom”,
                  “age”:22,
                  “country”:”USA”
      },
      {
                  “name”:”WangMing”,
                  “age”:25,
                  “country”:”China”
      }
      ]
      }

3. Use JSON parser
You can use the JSON parser to create JSON text from objects and arrays or to create objects and arrays from JSON text. The JSON website www.json.rog/json.js provides a JSON parser, which can be used by adding the following code to the head of the page. The JSON parser provides two functions: toJSONString() and parseJSON().
The toJSONString() method is added to the JavaScript Object and Array definitions. This method can convert JavaScript objects or arrays into JSON text. You don't have to convert the object or array to a literal to use this method.
The parseJSON() method can create objects or arrays from JSON text.
 (2) Use the XMLHttpRequest object to create a JSON data request
1. Create a request
If you directly request JSON data in a JSON file on the server, you can use the file name to request the JSON file.
  respone.open(“GET”,”classes.txt”,true);
  In this case, classes.txt is the name of the JSON data file, and request is the variable created to store the XMLHttpRequest object.
2. Parse the response
Once you accept the JSON data from the server, you can parse the response in two different ways. You can use JavaScript's built-in function eval(), or for further safety, use a JSON parser instead.
The eval() method can take a JavaScript string as a parameter, and can also convert the string into an object or as a command action. If you request JSON data using the responseText property of the XMLHttpRequest object, use eval() to convert the JSON text string into a JavaScript object. Because JSON strings often contain curly braces, use parentheses to surround the JSON string to indicate that it is an evaluated expression rather than a command to be run.
var jsonResp=request.responseText;
jsonResp=eval(“(”+jsonResp+”)”);
If the web server provides both JSON data and request pages, the eval() method is suitable. If security is involved, a JSON parser is appropriate. The JSON parser only works on JSON text and does not execute other JavaScript. In this case, you can use responseText, but use the parseJSON() method to convert the JSON text string into a JavaScript object. To access the parseJOSN function, you need to add a reference to the json.js file to the page.
var jsonResp=request.responseText;
jsonResp=jsonResp.parseJSON();
The following is an example to illustrate the simple use of JSON in JavaScript:

  <script type="text/javascript">
      var user =[
      {
            "name":”shenmiweiyi”,
            "QQ":306451129,
            "email":”shenmiweiyi@163.com”
            "address":
            [
                  {"City":"ZhengZhou","ZipCode":"450000"},
                  {"City":"BeiJing","ZipCode":"100000"}
            ]
      },
      {
            "name":”kehao”,
            "QQ":254892313,
            "email":”kehao@163.com”
            "address":
            [
                  {"City":"ShangHai","ZipCode":"200000"},
                  {"City":"GuangZhou","ZipCode":"510000"}
            ]
       }
      ]
      alert(user[0].name+”的Email是:”user[0].email);  //outputs shenmiweiyi的Email是:shenmiweiyi@163.com
       alert(user[1].name+”住在:”user[1].address[0].city) //outputs kehao住在:ShangHai
</script>

JSON is already part of the JavaScript standard. At present, mainstream browsers have perfect support for JSON. By using JSON, we can get rid of XML parsing. For those Web2.0 websites that use Ajax, JSON is indeed the most flexible and lightweight solution at present.

JSON is formatted as a JavaScript object

The JSON format is syntactically the same as the code that creates the JavaScript object.

Because they are similar, JavaScript programs can easily convert JSON data into JavaScript objects.

JSON syntax rules

Data is key/value pairs.

Data is separated by commas.

Braces save the object

Square brackets save the array

JSON data - one name corresponds to one value

JSON data format is key/value pair, that is Like JavaScript object properties.

Key/value pairs consist of the field name (in double quotes), followed by a colon, and then the value:

"firstName":"John"

JSON Object

JSON objects are stored within curly braces.

Just like in JavaScript, objects can hold multiple key/value pairs:

{"firstName":"John", "lastName":"Doe"}

JSON array

JSON array is stored in square brackets.

Just like in JavaScript, arrays can contain objects:

"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]

In the above example, the object "employees" is an array. Contains three objects.

Each object is a record of an employee (last name and first name).

Convert JSON string to JavaScript object

Usually we read JSON data from the server and display the data in the web page.

For the sake of simplicity, we set the JSON string directly in our web page (you can also read our JSON tutorial):

First, create a JavaScript string, and the string is data in JSON format:

var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName" :"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';

Then, use The JavaScript built-in function JSON.parse() converts a string into a JavaScript object:

var obj = JSON.parse(text);


Continuing Learning
||
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <h2>为 JSON 字符串创建对象</h2> <p id="demo"></p> <script> var text = '{"employees":[' + '{"firstName":"John","lastName":"Doe" },' + '{"firstName":"Anna","lastName":"Smith" },' + '{"firstName":"Peter","lastName":"Jones" }]}'; obj = JSON.parse(text); document.getElementById("demo").innerHTML = obj.employees[1].firstName + " " + obj.employees[1].lastName; </script> </body> </html>
submitReset Code