Detailed Explanation of JSON Data and Analysis of Example Code

  • 2021-07-13 03:45:09
  • OfStack

Detailed Explanation of JSON Data

1. Type of json value

1. Simple value: Can represent string, numeric value, Boolean value, null does not support undefined (numeric representation of json: 2)

2. Objects: An ordered set of key-value pairs, each of which can have a simple value or a complex data type. (json string: "hello world"). The difference between json string and JavaScript string is that json must be in double quotation marks.

3. Array: A list of 1 ordered set of values. The values of an array can be simple values or complex data types.

Variables, functions, and object instances are not supported

2. json objects versus javascript objects

Difference:


  //javascript Object 
   var obj = {
    name: "liu",
    age: 33,
   };


   // json Object 
   {
    "name": "liu",
    "age": 33,
   }

No variables are declared (there is no variable in json) There is no ending semicolon () Attributes in json are also enclosed in double quotation marks

3. String to json object conversion

1. JSON. parse (). parse parses a string into a native javascript value (javascript object); Each property name must be in double quotation marks


var str = '{"name":"huangxiaojian","age":"23"}';
console.log(JSON.parse(str)); //Object { name: "huangxiaojian", age: "23" }

Receive another parameter, which is the filter function (filter) that distinguishes JSON. stringify (), so it is called reduction function. As follows:


var book = {
     title: "hello",
     author: [ "apple" ],
     year: 300,
     releaseDate: new Date(2016)
    };

    var jsonText = JSON.stringify( book )
    var bookCopy = JSON.parse( jsonText, function( key, value ) {
     if (key == "releaseDate" ) {
      return new Date( value );
     } else {
      return value;
     }
    } );
    console.log( bookCopy.releaseDate.getFullYear() );

The above code book object has an releaseDate attribute, which saves Date object, becomes an effective JSON data string after serialization, and then restores it to an Date object after parsing in bookCopy. When encountering releaseDate key value, a new Date object will be created based on the corresponding value, and the result is that bookCopy. releaseDate attribute saves a new Date object.

2. JSON. stringify (object, selector, retract) objects, filters (arrays or functions), leaving indentation.

JSON. stringify () serializes an json object into a string. (Ignore functions, prototypes)


var a = {a:1,b:2};
console.log(JSON.stringify(a)); //{"a":1,"b":2} Does not contain any space characters or indentation 

3. The second parameter of JSON. stringify (), the filter is array

Filter: It can be an array (if it is an array, keep some attributes in the array) or a function (if it is a function, pass two parameters: attributes and attribute values).


var person = {
 name: "liu",
 age: 33,
 eat: [ "apple" ],
 sex: "man"
}
var jsonText = JSON.stringify( person, ["eat", "age" ] )
console.log( jsonText ) //{"eat":["apple"],"age":33}

4. The second parameter of JSON. stringify () is a function

Function: Two parameters of the function (). The parameter in switch is the attribute name (required string). If it is undefined, the attribute is ignored. (This value parameter is the whole serialized object.)

Note in particular that value is presented differently from mine in javascript Advanced Programming Edition 3. Maybe there is something wrong with my understanding, but I tested it and the result is also a serialized value. Who can solve it can tell me. (page: 566 ~ 567)


 var person = {
   "name": "liu",
   "age": 33,
   "eat": [ "apple" ],
   "sex": "man"
  }
  var jsonText = JSON.stringify( person, function( key, value ) {
   // console.log( value )
   switch("eat") {
    case "eat":
    return [3,4,5,5,5].join(",");
    case "age":
    return 33;
    case "sex":
    return undefined;
    default:
    return value;            
   }
  } )
  console.log( jsonText ) //"3,4,5,5,5"

5. Indent, with a maximum indentation of 10. If it exceeds 10, it will be converted to 10


 var person = {
   "name": "liu",
   "age": 33,
   "eat": [ "apple" ],
   "sex": "man"
  }
  var jsonText = JSON.stringify( person, null, 4 ) 
  console.log( jsonText )


///////////////////////// As a result, with the format ////////////////////
{
 "name": "liu",
 "age": 33,
 "eat": [
  "apple"
 ],
 "sex": "man"
}

 

  // Special indentation 
  var jsonText = JSON.stringify( person, null, "---" ) 
  console.log( jsonText )
///////////////////////// As a result, with the format ////////////////////
{
---"name": "liu",
---"age": 33,
---"eat": [
------"apple"
---],
---"sex": "man"
}

6. The toJSON () method, which returns its own json data format.


 var date = new Date()
  console.log( date.toJSON() ) 

 //person Not in oneself json Data format, this is wrong. 
  var person = {
   "name": "liu",
   "age": 33,
   "eat": [ "apple" ],
   "sex": "man"
  }
console.log( person.toJSON() ) 

7. Add toJSON () method to the object, and the returned string is in string format, the object is in object format, and a single numeric value is in numeric format.


var person = {
     "name": "liu",
     "age": 33,
     "eat": [ "apple" ],
     "sex": "man",
     "toJSON": function () {
      return this.age
     }
    }
    console.log( person.toJSON() ) // 33

toJSON () can be used as filter supplement

8. Suppose an object is passed in JSON. stringify (), serialize the order in which the object is

If an toJSON () method exists and a valid value can be obtained, the method is called; Otherwise, it is serialized in the default order. If the second parameter is supplied, this function filter is applied, and the value passed into the function filter is the return value of step 1. Serialize each value returned in Step 2. If the third parameter is provided, the corresponding formatting is performed.

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: