The web front end parsing json

Foreword

This is also the study notes do when the front end of the w3school, primarily to talk about the simple JSON-related knowledge

json syntax rules

JSON syntax derived JavaScript Object Notation grammar, syntax is a subset of JavaScript:

数据在名称/值对中
数据由逗号分隔
花括号容纳对象
方括号容纳数组

Example:

{"employees":[
    { "firstName":"Bill", "lastName":"Gates" },
    { "firstName":"Steve", "lastName":"Jobs" },
    { "firstName":"Elon", "lastName":"Musk" }
]}

JSON data written as name / value pairs. Name / value consists of a field name followed by a colon and values: "{name":"Bill Gates}"
the JSON name require double quotes. The name does not require JavaScript. JSON - as JavaScript object, almost equivalent to JavaScript object format.
In JSON, the key must be a string, and surrounded by double quotes. Value must be one of the following data types:

字符串(必须用双引号)
数字(整数或浮点数)
对象(JSON 对象)
数组
boolean
null

JavaScript JSON syntax portion due succession, it can be used as a JavaScript object with an array of values JSON
JSON as a data format, but may be a JavaScript object, which is similar to JavaScript property access mode, can also be used for-inwhile using obj[property]access objects, and the value of the object can be nested json json another object whose access mode is used by the access point number and the bracket nested JSON object is similar modification and deletion of general objects in JavaScript Example:

x = myObj.cars.car2;
//或者:
x = myObj.cars["car2"];

JSON value may be an array or an object (including JSON), the value of which can be nested with each other, similar to the above modification and deletion

Common method

Use JSON.parse () the text into a JavaScript object:

var obj = JSON.parse('{ "name":"Bill Gates", "age":62, "city":"Seattle"}');

NOTE: Date \ JSON functions, and so can not write to the data, to be converted into a string format is required to read out the date string into reviver function may be used, for example:

var text =  '{ "name":"Bill Gates", "birth":"1955-10-28", "city":"Seattle"}';
var obj = JSON.parse(text, function (key, value) {
    if  (key == "birth") {
        return new Date(value);
    } else {
         return value;
   }});
 
//函数的转换,避免在 JSON 中使用函数,函数会丢失它们的作用域
var text =  '{ "name":"Bill Gates", "age":"function () {return 62;}", "city":"Seattle"}';
var obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");

Use XMLHttpRequest get JSON data from the server:

var xmlHttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()  {
    if (this.readyState == 4 && this.status == 200) {
        myObj =  JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML  = myObj.name;
    }
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();

//作为json的数组
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()  {
    if (this.readyState == 4 && this.status == 200) {
        myArr =  JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML  = myArr[0];
    }
};
xmlhttp.open("GET", "json_demo_array.txt", true);
xmlhttp.send();

Using the JSON.stringify () the JavaScript object / array / date converted to a string , the function will be played if it is removed from the JavaScript object, comprising keys and values (unless it has been converted into a string):

var obj = { name:"Bill Gates", age:62, city:"Seattle"};
var myJSON = JSON.stringify(obj);

//数组转换
var arr = [ "Bill Gates", "Steve Jobs", "Elon Musk" ];
var myJSON = JSON.stringify(arr);

Common applications

HTML table

Using the received data to be generated as JSON form:

obj = { "table":"customers", "limit":20 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4  && this.status == 200) {
        myObj = JSON.parse(this.responseText);
         txt += "<table border='1'>"
        for (x in myObj) {
             txt += "<tr><td>" + myObj[x].name + "</td></tr>";
        }
        txt += "</table>" 
        document.getElementById("demo").innerHTML  = txt;
    }
}
xmlhttp.open("POST", "json_demo_db_post.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
Dynamic HTML table

HTML table based on the value of the drop-down list: Select an option: Customers Products Suppliers

<select id="myselect" onchange="change_myselect(this.value)">
    <option value="">Choose an option:</option>
    <option value="customers">Customers</option>
    <option value="products">Products</option>
    <option value="suppliers">Suppliers</option>
</select>

<script>
function  change_myselect(sel) {
    var obj, dbParam, xmlhttp, myObj,  x, txt = "";
    obj = { "table":sel, "limit":20 };
     dbParam = JSON.stringify(obj);
    xmlhttp = new  XMLHttpRequest();
    xmlhttp.onreadystatechange =  function() {
        if (this.readyState  == 4 && this.status == 200) {
             myObj = JSON.parse(this.responseText);
             txt += "<table border='1'>"
             for (x in myObj) {
                 txt += "<tr><td>" + myObj[x].name + "</td></tr>";
             }
            txt +=  "</table>" 
             document.getElementById("demo").innerHTML = txt;
         }
    };
    xmlhttp.open("POST", "json_demo_db_post.php",  true);
    xmlhttp.setRequestHeader("Content-type",  "application/x-www-form-urlencoded");
    xmlhttp.send("x="  + dbParam);
}
</script>
HTML drop-down list

With JSON data received to generate HTML dropdown list:

obj = { "table":"customers", "limit":20 };
dbParam = JSON.stringify(obj);
 xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4  && this.status == 200) {
        myObj = JSON.parse(this.responseText);
         txt += "<select>"
        for (x in myObj) {
             txt += "<option>" + myObj[x].name;
        }
        txt += "</select>" 
        document.getElementById("demo").innerHTML  = txt;
    }
}
xmlhttp.open("POST", "json_demo_db_post.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);

JSONP

JSONP refers JSON with Padding, you can transfer JSON data which does not require consideration of cross-domain problems. Request file from another domain can cause problems, due to the cross-domain policy. Request an external script from another domain do not have this problem .JSONP use of this advantage and use the script tag alternative XMLHttpRequest object.

Quote

https://www.w3school.com.cn/js/js_json_intro.asp

Released seven original articles · won praise 1 · views 128

Guess you like

Origin blog.csdn.net/weixin_43694216/article/details/104709027