1. What is JSON?

  • JSON, also known as JavaScript Object Notation, stands for JavaScript Object Notation.
  • JSON is a light-meight, text-based, human-readable format.
  • JSON has JavaScript in its name, but this means that its syntax rules refer to JavaScript objects, not to the JavaScript language.
  • JSON is easy to read and write for both humans and machines, and with smaller files than XML(another common data interchange format), it is quickly becoming a very popular interchange format on the Web.
  • JavaScript has become the de facto standard language on browsers in recent years, and the popularity of JSON is also closely related to the popularity of JavaScript.
  • Because JSON itself is defined by rules that refer to JavaScript objects, the syntax is almost identical to the syntax JavaScript uses to define objects.
  • The founders of the JSON format claim that the format is never upgraded, which means that the format is stable over time and that files written 10 years ago will work 10 years later without any compatibility issues.

2. What are the syntax rules of JSON?

The syntax rules for JSON are so simple that they can be described as “elegant and perfect.” They can be summarized as follows:

  • Arrays use square brackets (“[]“Said).
  • Object (0bject) with braces (“{}“Said).
  • Name/value pairs (name/value) into arrays and objects.
  • Name (name) inDouble quotation marksThe value (value) haveStrings, values, booleans, null, objects, and arrays.
  • Juxtaposed data is interspersed with commas (“.“)
{
    "name": "xdr630",
    "favorite": "programming"
}

3. The JSON and XML

JSON is often compared to XML because JSON was born more or less to replace XNL. JSON has the following advantages over XML:

  • No closing tag, shorter length, faster read and write
  • It can be parsed directly by the JavaScript interpreter
  • You can use arrays

Both are

  • JSON:
{" name ":" xi moving ", "age" : 22, "fruits" : [" apple ", "pear", "grape"]}
  • XML:
<root> <name> </root> 22</age> <fruits>apple</fruit > </fruit >pear</fruit > </fruit >grape</ root> </root>

4. Parsing and generating JSON (JSON and JS objects are converted to each other)

  • In JavaScript, there are two methods related to this: json.parse and json.stringify.

    JSON and JS objects transfer to each other

  • In order to realize theJSON stringconvertJS object, the use ofJSON.parse()Methods:
<script bb0 var STR = '{"name": "age","age":22}'; var obj = JSON.parse(str); console.log(obj); </script>

  1. In order to realize theJS objectconvertJSON string, the use ofJSON.stringify()Methods:
<script bb0 var STR = '{"name": "age","age":22}'; var obj = JSON.parse(str); console.log(obj); var jsonstr = JSON.stringify(obj); console.log(jsonstr); </script>

5. JSON format specification

1. Object (0bject)

  • Object with curly braces (“{}“) enclosed in braces is a series of”Name/value pairs“, please see the concept map.

  • Two parallel pieces of data are separated by a comma (“.“). Note two points:
  • Use the English comma (“.“), instead of using the Chinese comma (“.“).
  • The last one.”Name/value pairs“Don’t add a comma after that
  • JSON online check syntax: https://www.json.cn/
  • You cannot use single quotes for Key/Value in JSON

  • (1) Array (2) Array (3)
  • An array represents a sequence of ordered values, using square brackets (“[]“) and used between parallel valuesThe commaSeparate, see concept map.

  • For example, the following array is legal:
[1, 2, "three", "four", true, false, null, [1, 2], {" name ":" xi moving "}]

3. Name/Value

  • A Name is a string that is enclosed in double quotation marks, not single or no quotation marks, unlike JavaScript.
  • There are only seven types of values:String, number, object, array, true, false, null.There can’t be any type outside of this, such as uNdefined, functions,And so on. Look at the concept map.

The rules for string are as follows:

  1. English double quotation marks, can not use single quotation marks, can not be without.
  2. Strings cannot be separated by double quotes (") and the right slash (“\“).
  3. To use double quotation marks or a right slash, use”Right slash + character“In the form, for example\"and\ \The same is true for other escape characters.

  4. Escape character

    {
    "string":"\\ \" "
    }

  • A numeric type that can be represented using scientific notation
{
"number":1e3,
"n1":1e2,
"n2":-100
}

6. Convert strings to objects

  • Parsing: The process of converting a string to an object that conforms to the rules of JSON syntax.
  • Different programming languages provide ways to parse JSON strings, but here I’ll focus on parsing methods in JavaScript. There are three main types:
  • useeval()
  • useJSON.parse()
  • Use third-party libraries such as jQuery

1, the eval ()

  • The eval ()The argument to the function is a string, which is used to execute the JavaScript code in it directly.
  • Example: eval() parses a string

    <script>
      var str = "console.log('hello')";
      eval(str);
    </script>
  • Eval parses the result of a string:

  • Eval () can parse a JSON string. As you can see from this, JSON and JavaScript are highly chimeric.
  • Example: eval() to parse a JSON string

    <script bb0 var STR = '{"name":" age","age":22}'; var obj = eval("("+str+")"); console.log(obj) </script>

  • However, it’s rare to use eval() directly for parsing these days, and if your browser version is really old, you might need this method. In addition, eval() is a relatively dangerous function because strings can contain unknowns. Here again, as a way of learning, it’s important to know that this is also a method.
  • Notice that the eval() argument is bracketed around the string, which is required, otherwise an error will be reported.
  • Because the JSON string is enclosed by curly braces (“{}“) surrounded byeval()Will be executed as a block of statements, so parentheses will be added to make it an expression.

2, JSON. The parse ()

  • Most browsers now support itJSON.parse().“Is the recommended method.
  • If you enter a string that does not conform to the specification, an error will be reported.

Example: Convert a JSON string to a JS object

<script bb0 var STR = '{"name":" age","age":22}'; var obj = JSON.parse(str) console.log(obj) </script>

  • JSON.parse()You can take a second argument, which is a function. This function takes two arguments:The name and valueRepresents a name and a value, respectively. When passed in a JSON string, each set of JSONName/value pairsTo call this function. This function has a return value, which is assigned to the current name.
  • With the second argument, you can do some processing on the data while parsing the JSON string.

Case study:

<script bb0 var STR = '{"name":" age","age":22}'; var obj = JSON.parse(str,fun); function fun(name,value){ console.log(name+":"+value); return value } console.log(obj) </script>

  • When the JSON string name=age, set the age value to 14
<script bb0 var STR = '{"name":" age","age":22}'; var obj = JSON.parse(str,fun); function fun(name,value){ if (name == "age") value = 14; return value } console.log(obj) </script>

7. JS objects are converted to strings

  • Serialization, which refers to the process of converting JavaScript values into JSON strings.
  • JSON. Stringify ()Ability to convert JavaScript values to JSON strings.JSON.stringify()The generated string can be usedJSON.parse()Restore to JavaScript values.

1. The meaning of parameters

JSON.stringify(value[, replacer[, space]])
  1. value: Required parameter. The JavaScript value being transformed, typically an object or an array.
  2. replace: It can be omitted. There are two options: functions or arrays.
  3. If it is a function, then this function is called for each set of name/value pairs, and this function returns a value that is transformed into the result string as the value of the name, if returnedundefined, the member is ignored.

Case study:

<script> var obj = {name: "", age: 22}; console.log(obj); var jsonstr = JSON.stringify(obj,fun); function fun(name,value) { if (name=="age") value = 18; return value; } console.log(jsonstr) </script>

  • If it is an array, then only the name in the array can be converted, and the order of conversion is the same as the value in the array.
  • Case study:
<script>
        var obj = {
            a: 1,
            b: 2,
            c: 3,
            d: 4
        };
        console.log(obj);

        var jsonstr = JSON.stringify(obj,["a","b","c"]);
        
        console.log(jsonstr)
</script>

  • Change the order so that the value of the JSON string corresponding to the conversion remains the same
var jsonstr = JSON.stringify(obj,["c","a","b"]);

  1. space: It can be omitted. This is for typesetting, easy to read and exist. You can add whitespace, tabs, etc to the JSON string.

2. Usage of value

<script> var obj = {name: "age ", age: 22} console.log(obj); var jsonstr = JSON.stringify(obj); console.log(jsonstr) </script>

  • When something does not conform to the JSON syntax rules, it is not converted to a JSON string.
  • When there’s a function in an array, it gets converted tonull
Function () {}, b:[function () {}, b:[function () {}]} console.log(obj); var jsonstr = JSON.stringify(obj); console.log(jsonstr) </script>

3. Use of replace

4. Use of space

  • Case: Add on top of the above
<script>
        var obj = {
            a: 1,
            b: 2,
            c: 3,
            d: 4
        };
        console.log(obj);

        var jsonstr = JSON.stringify(obj,["c","a","b"],"one");

        console.log(jsonstr)
</script>

  • Change to TAB character:\t
<script>
        var obj = {
            a: 1,
            b: 2,
            c: 3,
            d: 4
        };
        console.log(obj);

        var jsonstr = JSON.stringify(obj,["c","a","b"],"\t");

        console.log(jsonstr)
</script>