Detailed Explanation of json Basic Knowledge in javascript

  • 2021-07-12 04:59:31
  • OfStack

A general introduction

JSON (JavaScript Object Notation JavaScript object notation), JSON is a data format, not a programming language. Although it has JavaScript in its name, it does not belong to JavaScript, just like the relationship between Java and JavaScript. Moreover, it is not only used by JavaScript, after all, JSON is only a data format. Many programming languages have parsers and serializers for JSON.

JSON was proposed by Douglas Crockford in 2001 to replace XML

Grammar

The syntax of JSON can contain three types of values:

Simple value

Object

Array

Simple value

Simple Values: Using the same syntax as JavaScript, you can represent strings, numeric values, Boolean values, and null in JSON

Note: "1" JSON does not support the special value undefined in JavaScript

'2' JSON strings must use double quotation marks (single quotation marks can cause syntax errors)


 //  Effective JSON Data 
 "Hellow World!"
 5
 true
 null

Object

Object, as a complex data type, represents a set of ordered key-value pairs, and the values in each key-value pair can be either simple values or complex data types

Objects in JSON differ slightly from literals in JavaScript by 1:

1. No variables are declared

2. No semicolons at the end

3. The attribute names of objects in JSON must be enclosed in double quotation marks at all times

Note: Two properties with the same name should never appear in the same object


// JavaScript Literal quantity in 
 var person = {
 name : "Lao Wang",
 age : 21
 };
 // JSON
 {
 "name" : "Lao Wang",
 "age" : 21
 }
 //  You can embed objects in objects 
 {
 "name" : "Lao Wang",
 "age" : 21,
 "school" :   {
 "name" : "TJLG",
 "location" : " Xiqing "
 }
 }

Array

JSON arrays take the literal form of arrays in JavaScript


 // JavaScript
 var values = [21," Xiqing ",true];
 // JSON
 values = [21," Xiqing ",true]

JSON Object

The early JSON parser basically used the eval () function of JavaScript. Since JSON is a subset of JavaScript syntax, eval () function can parse, interpret and return JavaScript objects and arrays. However, using eval () function to evaluate JSON data structure is risky and may execute some malicious code, so use eval () function as little as possible

ECMAScript 5 regulates the behavior of parsing JSON and defines the global object JSON. The browsers that support this object are IE 8 +, Firefox 3.5 +, Safari 4 +, Chrome, and Opera 10.5 +. For earlier versions of browsers, you can use one shim: https://github. com/douglascrockford/JSON-js.

The JSON object has two methods:

1. stringify ()

2. parse ()

stringify()

The stringify () method serializes an JavaScript object into an JSON string

Note:

"1" By default, the JSON string output from JSON. stringify () does not contain any space characters or indentation


var person = {
 name : "Lao Wang",
 grade : {
 "English" : "88",
 "Math" : "98"
 }
 };
 var jsonPerson = JSON.stringify(person);
 console.log(jsonPerson);
 // {"name":"Lao Wang","grade":{"English":"88","Math":"98"}}

"2" If a member of an object is an undefined or a function, that member is ignored

If the members of the array are undefined or functions, these values are converted to null


var person = {
 name : function(){},
 sex : undefined,
 age : 21,
 grade : [undefined,function(){},"English"],
 }
 var jsonPerson = JSON.stringify(person);
 console.log(jsonPerson);
 // {"age":21,"grade":[null,null,"English"]}

"3" JSON. stringify () ignores non-traversible properties of objects


var person = {};
 Object.defineProperties(person,{
 'name' : {
 value : "Lao Wang",
 enumerable : true
 },
 'age' : {
 value : 21,
 enumerable : false
 }
 });
 var jsonPerson = JSON.stringify(person);
 console.log(jsonPerson);
 // {"name":"Lao Wang"}

In fact, JSON. stringify () can take two other parameters in addition to the JavaScript object to be serialized, which are used to specify that the JavaScript object should be serialized differently

The first argument is a filter, which can be an array or a function

The second parameter is an option indicating whether to keep indentation in the JSON string

1. When the first parameter is an array

If the filter parameter is an array, the result of JSON. stringify () will contain only the attributes listed in the array

Note:

'1', the filter is only valid for Layer 1 properties of the object


var person = {
 name : "Lao Wang",
 grade : {
 "English" : "88",
 "Math" : "98"
 }
 };
 var jsonPerson = JSON.stringify(person,["name","Math"]);
 console.log(jsonPerson);
 // {"name":"Lao Wang"}

'2' filter is not valid for arrays


 var values = [21,"he",true,"we"];
 var jsonValues = JSON.stringify(values,["he"]);
 console.log(jsonValues);
 // [21,"he",true,"we"]

2. When the first argument is a function

The passed-in function takes two arguments, the property (key) name and the property value. According to the property (key) name, you can know what to do with the properties in the object to be serialized. The property name can only be a string, and the key name can be an empty string when the value is not the value of a key-value pair structure. To change the result of serializing the object, the value returned by the function is the value of the corresponding key.

Note: If the function returns undefined or does not return a value, the corresponding property is ignored


var values = {
 name : "Lao Wang",
 age : 21,
 sex : " Male "
 }
 var jsonValues = JSON.stringify(values,function(key,value){
 if(key == "sex"){
 return undefined;
 }else{
 return value;
 }
 });
 console.log(jsonValues);
 // {"name":"Lao Wang","age":21}

3. When the third parameter is given,

The third parameter of the JSON. stringify () method controls indentation and white space in the result. If this parameter is a numeric value, it represents the number of spaces indented at each level

Note:

"1" As long as a valid parameter value controlling indentation is passed in, the resulting string will contain a newline character

"2" Maximum number of indent spaces is 10. All values greater than 10 are automatically converted to 10

"3" If the indentation parameter is a string instead of a numeric value, this string will be used as the indentation character in the JSON string (no longer using spaces)


//  Parameters are numeric values 
 var person = {
 name : "Lao Wang",
 grade : {
 "English" : "88",
 "Math" : "98"
 }
 };
 var jsonPerson = JSON.stringify(person,null,4);
 console.log(jsonPerson);
 /*
 {
 "name": "Lao Wang",
 "grade": {
 "English": "88",
 "Math": "98"
 }
 }
 */
 //  Parameter is a string 
 var person = {
 name : "Lao Wang",
 grade : {
 "English" : "88",
 "Math" : "98"
 }
 };
 var jsonPerson = JSON.stringify(person,null,"-_-||");
 console.log(jsonPerson);
 /* 
 {
 -_-||"name": "Lao Wang",
 -_-||"grade": {
 -_-||-_-||"English": "88",
 -_-||-_-||"Math": "98"
 -_-||}
 }
 */

toJSON()

Sometimes, JSON. stringify () does not meet the need for custom serialization of certain objects. In these cases, you can call the toJSON () method through the object to return its own JSON data format


// JavaScript Literal quantity in 
 var person = {
 name : "Lao Wang",
 age : 21
 };
 // JSON
 {
 "name" : "Lao Wang",
 "age" : 21
 }
 //  You can embed objects in objects 
 {
 "name" : "Lao Wang",
 "age" : 21,
 "school" :   {
 "name" : "TJLG",
 "location" : " Xiqing "
 }
 }
0

Note: If the toJSON () method returns undefined, if the object containing it is embedded in another object, it will cause the value of that object to become null. And if the object containing it is a top-level object, the result is undefined


// JavaScript Literal quantity in 
 var person = {
 name : "Lao Wang",
 age : 21
 };
 // JSON
 {
 "name" : "Lao Wang",
 "age" : 21
 }
 //  You can embed objects in objects 
 {
 "name" : "Lao Wang",
 "age" : 21,
 "school" :   {
 "name" : "TJLG",
 "location" : " Xiqing "
 }
 }
1

The native Date object has an toJSON () method that automatically converts the Date object of JavaScript to an ISO 8601 date string (exactly the same as the result of calling toISOString () on an Date object)


// JavaScript Literal quantity in 
 var person = {
 name : "Lao Wang",
 age : 21
 };
 // JSON
 {
 "name" : "Lao Wang",
 "age" : 21
 }
 //  You can embed objects in objects 
 {
 "name" : "Lao Wang",
 "age" : 21,
 "school" :   {
 "name" : "TJLG",
 "location" : " Xiqing "
 }
 }
2

toJSON () can be used as a complement to the function filter, so it is important to understand the internal order of serialization. Suppose you pass an object into JSON. stringify () and serialize the object in the following order

1. If the toJSON () method exists and a valid value can be obtained from it, the method is called. Otherwise, serialization is performed in the default order

2. If the second parameter is provided, apply this function filter. The value passed into the function filter is the value returned in step 1

3. Serialize each value returned in Step 2 accordingly

4. If the third parameter is provided, perform the corresponding formatting

JSON. parse ()

JSON. parse () parses an JSON string to an JavaScript value


var person = JSON.parse('{"name":"Lao Wang"}');
console.log(person.name);
// Lao Wang

Note: If the string passed in is not in a valid JSON format, the JSON. parse method will report an error

The JSON. parse () method can also take another parameter, which is a function that will be called on each key-value pair. To distinguish the substitution (filter) function (replacer) that JSON. stringify () receives, this function is called the reduction function (reviver). The reduction function takes two arguments, a key and a value, and needs to return a value

Note: If the reduction function returns undefined, it means that the corresponding key is to be deleted from the result; If another value is returned, the value is inserted into the result


// JavaScript Literal quantity in 
 var person = {
 name : "Lao Wang",
 age : 21
 };
 // JSON
 {
 "name" : "Lao Wang",
 "age" : 21
 }
 //  You can embed objects in objects 
 {
 "name" : "Lao Wang",
 "age" : 21,
 "school" :   {
 "name" : "TJLG",
 "location" : " Xiqing "
 }
 }
4

The reduction function is often used when converting a date string to an Date object


// JavaScript Literal quantity in 
 var person = {
 name : "Lao Wang",
 age : 21
 };
 // JSON
 {
 "name" : "Lao Wang",
 "age" : 21
 }
 //  You can embed objects in objects 
 {
 "name" : "Lao Wang",
 "age" : 21,
 "school" :   {
 "name" : "TJLG",
 "location" : " Xiqing "
 }
 }
5

References:

Detailed Explanation of JSON Object and Example Code

JavaScript Advanced Programming Chinese Version 3


Related articles: