JSON Detailed Explanation of JavaScript Core Technology

What is JSON?

JSON (JavaScript Object Notation, JS Object Notation) is a lightweight data exchange format. It is based on a subset of ECMAScript (European Computer Manufacturers Association, the js specification developed by the European Computer Association), and uses a text format that is completely independent of the programming language to store and represent data. The simplicity and clear hierarchy make JSON an ideal data interchange language. It is easy for people to read and write, and it is also easy for machines to parse and generate, and it can effectively improve the efficiency of network transmission. 

JSON is derived from JavaScript and is a lightweight (Light-Meight), text-based (Text-Based), and human-readable (Human-Readable) format.

In the current development, there are two JSON XML formats that can be used for data exchange.

JSON is a syntax for storing and exchanging textual information. Similar to XML, JSON is smaller, faster, and easier to parse than XML.

 So, in a nutshell, the description of JSON is summarized as follows:

  • JSON is a data format independent of any programming language
  • is a lightweight format for storing and transferring data
  • Grammar is self-describing, easy for humans to read and understand

JSON syntax

Basic syntax:

  • Arrays are represented by square brackets "[]"
  • Objects (0bject) are represented by braces "{}"
  • Name/value pairs (name/value) combined into arrays and objects
  • The name ( name ) is placed in double quotes, and the value (value) has strings, numbers, booleans, null, objects, and arrays
  • Parallel data are separated by commas ","
  • A name/value pair consists of the field name (in double quotes), followed by a colon, then the value

have to be aware of is:

JSON does not support comments. Adding comments to JSON has no effect

The file type of the JSON file is .json

The type of JSON text  MIME is application/json

Get JSON data

 JSON exists in the form of objects, and the following methods can be used to directly obtain JSON data:

1. json object. key name

2. json object ["key name"]

3. Array Object [Index]

4. traverse 

Code example:

//定义基本格式
      var person = { name: "张三", age: 23, gender: true };
      var persons = [
        { name: "张三", age: 23, gender: true },
        { name: "李四", age: 24, gender: true },
        { name: "王五", age: 25, gender: false },
      ];

      //获取person对象中所有的键和值
      //for in 循环
      /* for(var key in person){
          //这样的方式获取不行。因为相当于  person."name"
          //alert(key + ":" + person.key);
          alert(key+":"+person[key]);
          }*/

      //获取persons中的所有值
      for (var i = 0; i < persons.length; i++) {
        var p = persons[i];
        for (var key in p) {
          console.log(key + ":" + p[key]);
        }
      }

 The output is:

 JSON parsing and serialization (in JavaScript)

First print the JSON object in the console to see what is there, as shown in the figure:

 Obviously, JSON objects have only two methods in JavaScript: parse and stringify. These two methods will be described in detail later

The concept of serialization: Serialization is the process of converting an object into a sequence of bytes. After the object is serialized, it can be transmitted on the network or saved to the hard disk.

Serialize the object into a json string: JSON.stringify(json object);

Deserialization: Deserialize the json string into an object: JSON.parse(str)

JSON.parse

API introduction: used to parse JSON strings, construct values ​​or objects described by strings  JavaScript , and an error will be reported if the incoming string does not conform to the JSON specification

grammar:

JSON.parse(str, reviver);
  • str: the JSON string to parse
  • reviver: An optional function  function(key,value), the first parameter and the second parameter of the function represent the key and value of the key-value pair respectively, and the value can be converted (the return value of the function is regarded as the processed value)

Code example:

// JSON.parse() 解析JSON字符串, 将JSON转换为对象
      let json = '{"name": ["js", "webpack"], "age": 22, "gridFriend": "ljj"}';
      console.log(JSON.parse(json)); 
      // {name: Array(2), age: 22, gridFriend: 'ljj'}

      // 第二个参数是一个函数,key和value代表每个key/value对
      let result = JSON.parse(json, (key, value) => {
        if (key == "age") {
          return `年龄:${value}`;
        }
        return value;
      });
      console.log(result);
      //{name: Array(2), age: '年龄:22', gridFriend: 'ljj'}

 JSON.stringify

API Introduction: Convert an  JavaScript Object or Value to a JSON String

If a function is specified  replacer , optionally replace values, or if  replacer an array is specified, optionally include only the properties specified by the array

grammar:

JSON.stringify(value, replacer, space)

value: the value to be serialized into a JSON string

replacer:

  • If the parameter is a function, each attribute of the serialized value will be converted and processed by the function during the serialization process
  • If the parameter is an array, only the property names contained in the array will be serialized into the final JSON string
  • If this parameter is null or not provided, all properties of the object will be serialized

space: Specifies the blank string for indentation, used to beautify the output

  • If the argument is a number, it represents how many spaces; the upper limit is 10. If the value is less than 1, it means there is no space
  • If the parameter is a string (when the length of the string exceeds 10 letters, take the first 10 letters), the string will be treated as a space
  • If this parameter is not provided (or is null), there will be no spaces

Code example:

      let obj = {
        name: "jsx",
        age: 22,
        lesson: ["html", "css", "js"],
      };
      let json = JSON.stringify(obj);
      console.log(json);
      // {"name":"jsx","age":22,"lesson":["html","css","js"]}

      // 第二个参数replacer 为函数时,被序列化的值得属性都会经过该函数转换处理
      function replacer(key, value) {
        if (typeof value === "string") {
          return undefined;
        }
        return value;
      }
      let result = JSON.stringify(obj, replacer);
      console.log(result);
      // {"age":22,"lesson":[null,null,null]}

      // 当replacer参数为数组,数组的值代表将被序列化成 JSON 字符串的属性名
      let result1 = JSON.stringify(obj, ["name", "lesson"]);
      // 只保留 “name” 和 “lesson” 属性值
      console.log(result1);
      // {"name":"jsx","lesson":["html","css","js"]}

      // 第三个参数spcae,用来控制结果字符串里面的间距
      let result2 = JSON.stringify(obj, null, 4);
      console.log(result2);
      /*{
          "name": "jsx",
          "age": 22,
          "lesson": [
              "html",
              "css",
              "js"
          ]
      }*/

 Note: If the replacer is a function, the function will perform deep processing, that is, if the value of the key-value pair is also an array, the function will also be executed

JSON.stringify() principle

  • Convert Value If there is  toJSON() a method, this method defines what value will be serialized
  • The properties of non-array objects are not guaranteed to appear in a specific order in the serialized string
  • Boolean values, numbers, and string wrapper objects will be automatically converted to corresponding primitive values ​​during serialization, and undefined, arbitrary functions, and symbol values ​​will be ignored during serialization (appearing in the property values ​​​​of non-array objects in) or converted to null (when present in an array). When functions and undefined are converted separately, undefined will be returned, such as JSON.stringify(function(){}) or JSON.stringify(undefined)
  • Executing this method on objects containing circular references (objects refer to each other, forming an infinite loop) will throw an error
  • All properties with a symbol as the property key will be completely ignored, even if they are mandatory to be included in the replacer parameter.
  • Date calls toJSON() to convert it to a string string (same as Date.toISOString()), so it will be treated as a string
  • NaN and Infinity format values ​​and null will be treated as null
  • Other types of objects, including Map/Set/WeakMap/WeakSet, only serialize enumerable properties

Guess you like

Origin blog.csdn.net/m0_65335111/article/details/127227162