JSON(json) detailed tutorial

Posted by moonie on Mon, 31 Jan 2022 17:47:08 +0100

1, What is JSON?

  • JSON is a format for storing and transmitting data.
  • JSON is usually used to transfer data from the server to the web page.
  • JSON refers to JavaScript Object Notation
  • JSON is a lightweight text data exchange format
  • JSON is language independent: JSON uses Javascript syntax to describe data objects, but JSON is still language and platform independent. The JSON parser and JSON library support many different programming languages. At present, many dynamic (PHP, JSP,. NET) programming languages support JSON
  • JSON is self descriptive and easier to understand

2, Syntax rules of JSON

JSON syntax is a subset of JavaScript syntax

Specific rules:

  1. Data in name / value pair
  2. Data is separated by commas
  3. Braces {} save objects
  4. Brackets [] hold arrays, which can contain multiple objects

1.JSON name / value pair

  • JSON written data format:
key:value//Key / value, also known as key value pair
  • The name / value pair includes the field name (in double quotes), followed by a colon, followed by the value:
"name":"JSON PRACTICE"

This is easy to understand and is equivalent to this JavaScript statement:

name="JSON PRACTICE"

2. Type of JSON value

JSON values can be:

1. Number (integer or floating point number)
{"age":30}
2. String (in double quotation marks)
{"name":"JSON PRACTICE"}
3. Logical value (true or false)
{"isKey":true}
4. Array (in square brackets). The array can contain multiple objects
[
    { key1 : value1-1 , key2:value1-2 }, 
    { key1 : value2-1 , key2:value2-2 }, 
    { key1 : value3-1 , key2:value3-2 }, 
    ...
    { keyN : valueN-1 , keyN:valueN-2 }, 
]
5. Object (in braces)
{key1 : value1, key2 : value2, ... keyN : valueN }
6. null
{"curriculum":null}

JSON uses JavaScript syntax

Because JSON uses JavaScript syntax, it can handle JSON in JavaScript without additional software. With JavaScript, you can create an array of objects and assign values like this:

var sites = [
    { "name":"baidu" , "url":"www.baidu.com" }, 
    { "name":"google" , "url":"www.google.com" }, 
    { "name":"weibo" , "url":"www.weibo.com" }
];

Accessing elements in an array of objects

name1=sites[0].name;

The result is: name1 = www.baidu com
You can also modify the data like this: sites [0] name="Learning"

JSON file

  • The file type of JSON file is json
  • The MIME type of JSON text is application/json

3, JSON and JS conversion

1.JSON. Parse() method

JSON is usually used to exchange data with the server.
When receiving server data, it is generally a string.

JSON. The function of the parse () method is to convert JSON data into JS objects

JSON.parse(text[, reviver])
//text: required, a valid JSON string
//reviver: optional, a function of conversion result, which will be called for each member of the object.
  • JSON parsing instance:
    For example, we received the following data from the server:
{ "name":"baidu","site":"www.baidu.com" }

We can use JSON The parse () method processes the above data and converts it into a JavaScript object:

var obj = JSON.parse('{"name":"baidu","site":"www.baidu.com" }');

We can use it this way:

sites=obj.name+" "+obj.site

The value of sites is: Baidu www.baidu.com com

  • Receive JSON data from the server
    We can use AJAX to request JSON data from the server and parse it into JavaScript objects.
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", "/try/ajax/json_demo.txt", true);
xmlhttp.send();
  • Receive the JSON data of the array from the server
    If the JSON data of the array is received from the server, JSON Parse converts it into a JavaScript array:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myArr = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = myArr[1];
    }
};
xmlhttp.open("GET", "/try/ajax/json_demo_array.txt", true);
xmlhttp.send();
  • Abnormal condition
    Parse data
    JSON cannot store Date objects.
    If you need to store a Date object, you need to convert it to a string.
    Then convert the string to a Date object.
var text = '{ "name":"baidu", "initDate":"2013-12-14", "site":"www.baidu.com"}';
var obj = JSON.parse(text);
obj.initDate = new Date(obj.initDate);
 
document.getElementById("demo").innerHTML = obj.name + "Creation date: " + obj.initDate;

We can enable JSON The second parameter of parse, reviver, is a function of the conversion result, which is called by each member of the object.

var text = '{ "name":"baidu", "initDate":"2013-12-14", "site":"www.baidu.com"}';
var obj = JSON.parse(text, function (key, value) {
    if (key == "initDate") {
        return new Date(value);
    } else {
        return value;
}});
 
document.getElementById("demo").innerHTML = obj.name + "Creation date:" + obj.initDate;

analytic function
JSON does not allow functions, but you can store functions as strings and then convert strings to functions.

var text = '{ "name":"baidu", "alexa":"function () {return 10000;}", "site":"www.baidu.com"}';
var obj = JSON.parse(text);
obj.alexa = eval("(" + obj.alexa + ")");
 
document.getElementById("demo").innerHTML = obj.name + " Alexa Ranking:" + obj.alexa();

Functions are not recommended in JSON.

2.JSON.stringlfy() method

JSON is usually used to exchange data with the server.
When sending data to the server, it is usually a string.
JSON. The stringlfy () method converts JavaScript objects into strings.

JSON.stringify(value[, replacer[, space]])
//Value: required, the JavaScript value to be converted (usually an object or array).
//Replace: optional. The function or array used to convert the result. If replace is a function, JSON Stringify will call this function and pass in the key and value of each member. Use the return value instead of the original value. If this function returns undefined, members are excluded. The key of the root object is an empty string: ''. If the replacement is an array, only the members with key values in the array are converted. The conversion order of members is the same as that of keys in the array. When the value parameter is also an array, the replace array is ignored.
//Space: optional. Indent, space and line feed are added to the text. If space is a number, the return value text is indented by a specified number of spaces at each level. If space is greater than 10, the text is indented by 10 spaces. Space can also use non numbers, such as: \ t.
  • JavaScript object conversion
    For example, we send the following data to the server:
var obj = { "name":"baidu", "site":"www.baidu.com"};

We use JSON The stringify() method processes the above data and converts it into a string:

var myJSON = JSON.stringify(obj);

myJSON is a string. We can send myJSON to the server:

var obj = { "name":"baidu","site":"www.baidu.com"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;
  • JavaScript array conversion
    We can also convert JavaScript arrays to JSON strings:
var arr = [ "Google", "Baidu", "Taobao", "Facebook" ];
var myJSON = JSON.stringify(arr);

myJSON is a string. We can send myJSON to the server:

var arr = [ "Google", "baidu", "Taobao", "Facebook" ];
var myJSON = JSON.stringify(arr);
document.getElementById("demo").innerHTML = myJSON;
  • Abnormal condition
    Parse data
    JSON cannot store Date objects.
    JSON.stringify() converts all dates to strings.
var obj = { "name":"baidu", "initDate":new Date(), "site":"www.baidu.com"};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON;

You can then convert the string to a Date object.
analytic function
JSON is not allowed to contain functions, JSON Stringify() will delete the functions of JavaScript objects, including key and value.

var obj = { "name":"baidu", "alexa":function () {return 10000;}, "site":"www.baidu.com"};
var myJSON = JSON.stringify(obj);
 
document.getElementById("demo").innerHTML = myJSON;

We can execute JSON Convert the function into a string before stringify() function to avoid the above problems:

var obj = { "name":"baidu", "alexa":function () {return 10000;}, "site":"www.baidu.com"};
obj.alexa = obj.alexa.toString();
var myJSON = JSON.stringify(obj);
 
document.getElementById("demo").innerHTML = myJSON;

Functions are not recommended in JSON.

I believe you should have a general understanding of JSON. If you think this article is useful to you, you can praise and support it!

Topics: Javascript Front-end JSON