Home > Article > Web Front-end > Detailed code explanation of the usage of JSON in JavaScript
Recently summarized some JavaScript knowledge and shared it with everyone. This article focuses on JSON, explaining the difference between JSON and XML, how to parse JSON text, and JSONP.
It has certain reference value. Friends in need can take a look. I hope it can help you.
1. What is JSON
JSON is JavaScript Object Notation, which is JavaScript object notation.
2. Comparison of JSON and XML
Similar points: both are a method of storing and exchanging text information.
Difference: JSON is smaller, faster, and easier to parse than XML. XML was all the rage before the emergence of JSON. XML had two main functions, namely storing data and transmitting data. However, as time went by, XML became unable to transmit data. Therefore, JSON, which was born later, replaced XML. So JSON is mainly used to transmit data, and XML is mainly used to store data. Regarding transmitting JSON in ajax, you can refer to the article A Brief Analysis of the Use of Ajax.
3. JSON syntax
The data is in the "name:value" pair, the data is separated by commas, curly brackets save the object, and square brackets save the array.
Common JSON writing methods:
var sites = [ { "name":"百度" , "url":"www.baidu.com" }, { "name":"Google" , "url":"www.google.com" }, ]; 或是: var tx = '{ "sites" : [' + '{ "name":"百度" , "url":"www.baidu.com" },' + '{ "name":"Google" , "url":"www.google.com" } ]}';
4. How to parse JSON text
When the javaScript class is written in the second situation above, JSON needs to be parsed , generate the corresponding javaScript object.
1, eval() method
This method is a built-in method of javaScript.
<!DOCTYPE html> <html> <head> <title>测试JSON</title> <meta name="content-type" content="text/html; charset=UTF-8"> </head> <body> <div id="name"> </div> <script> var tx = '{ "sites" : [' + '{ "name":"百度" , "url":"www.baidu.com" },' + '{ "name":"Google" , "url":"www.google.com" } ]}'; var obj = eval ("(" + tx + ")"); alert(obj.sites[0].name+","+obj.sites[0].url); </script> </body> </html>
There are two ways to access data in JSON, one is through object.key To obtain it, such as obj.sites[0].url; the other is to obtain it through the object ["key"], such as obj.sites[0]["key"]. The advantage of the first method is simplicity, and the advantage of the second method is to obtain the value of the JSON object through a string. This can be applied when the key of a string needs to be dynamically spliced, and then the corresponding value is obtained.
2, JSON.parse() method
Just replace the sentence parsed with the eval() method above with the following:
var obj = JSON .parse(tx);
3, JSON array
When accessing data with Ajax, we often parse the JSON data returned by the server, and the JSON array is compared Commonly used, next I will talk about the parsing of JSON arrays. To parse the SON array, you can use a for loop or a for...in... loop,
Use for-in to access the array:
<body> <p>你可以使用 for-in 来访问数组:</p> <p id="demo"></p> <script> var myObj, i, x = ""; myObj = { "name":"网站", "num":3, "sites":[ "Google", "Runoob", "Taobao" ] }; for (i in myObj.sites) { x += myObj.sites[i] + "<br>"; } document.getElementById("demo").innerHTML = x; </script> </body>
Use for loop to access the array:
<body> <p>使用 for 循环访问数组:</p> <p id="demo"></p> <script> var myObj, i, x = ""; myObj = { "name":"网站", "num":3, "sites":[ "Google", "Runoob", "Taobao" ] }; for (i = 0; i < myObj.sites.length; i++) { x += myObj.sites[i] + "<br>"; } document.getElementById("demo").innerHTML = x; </script> </body>
MyObj.sites.length can get the length of the sites array.
5. How to parse JSON objects
If you need to parse JSON into JSON text, then you only need to use the function:
var JSONString = JSON. stringify(JSONObject);
The stringify function will not parse the function, it will delete the function in the object. We can convert the function into a string to solve this problem
var obj = { " name":"Runoob", "alexa":function () {return 10000;}, "site":"www.runoob.com"};
//Convert the function into a string
obj.alexa = obj.alexa.toString();
var myJSON = JSON.stringify(obj);
6. JSONP
What is JSONP: JSONP(json width padding), a usage pattern of json.
What does JSONP do: It can enable web pages to obtain data from other domain names, that is, read data across domains.
Why use JSONP: Because of the same-origin policy (a security policy proposed by NetScape).
Use JSP to implement JSONP
<!DOCTYPE html> <html> <head> <title>jsonp.html</title> <meta name="content-type" content="text/html; charset=UTF-8"> </head> <body> <script type="text/javascript"> function jsonpCallback(result){ alert(result[1].name); } </script> <script type="text/javascript" src="http://localhost:8080/Jsonp/jsonp.jsp?callback=jsonpCallback"></script> </body> </html>
The complete code of the server:
<% String callback = request.getParameter("callback"); out.print(callback+"([ { name:'John',age:'19'},{ name:'joe',age:'20'}] );"); %>
Code explanation:
The one who calls the data is the client, and the one who sends the data is called the server. In the code that accesses the URL of the server, the client adds a parameter with a specified function name, which is jsonCallback, then uses getParameter to obtain the data on the server, and finally outputs it to the stream according to the syntax of js. Readers need to note here that the data on the server side above is the entire jsp file content. In addition to using jsp, readers can also use php or jquery and other technologies to implement the server side, but the suffix name and the syntax used must be consistent.
The above is the detailed content of Detailed code explanation of the usage of JSON in JavaScript. For more information, please follow other related articles on the PHP Chinese website!