Detailed Explanation of JSON and js Object Serialization Instances

  • 2021-08-05 08:04:20
  • OfStack

This article illustrates the serialization of JSON and js objects. Share it for your reference, as follows:

JavaScript Object Notation (JavaScript Object Notation, JSON for short) is a lightweight data exchange format, which is based on js literal notation and is a subset of js. Although it is a subset of js, it is language independent and can be used to exchange data between applications written in all current programming languages. It is a text format, which is easy to read and write.

JSON is an unordered collection of "name/value" pairs, the name can be any string, and the value can be any value of JSON type. Most programming languages have data types mapped to JSON, such as objects (object), dictionaries (dictionary), hash tables (hash map), associative arrays (associative array), and so on.

JSON has six types of values: object, array, string, number, Boolean, and special value null.


console.log(JSON.parse('5')); // 5
console.log(JSON.parse(5)); // 5
console.log(JSON.parse('true')); // true
console.log(JSON.parse(true)); // true
console.log(JSON.parse('"hello"')); // "hello"
console.log(JSON.parse("hello")); //  Report an error   Because hello No JSON String 
console.log(JSON.parse('null')); // null
console.log(JSON.parse(null)); // null
console.log(JSON.parse(undefined)); //  Report an error   Because JSON Cannot indicate undefined Switch to null Substitute 

Structure of JSON

JSON has two structures: an object, an array

The object structure begins with a "{" brace and ends with a "}" brace. The middle part is composed of 0 or more pairs of "key (keyword)/value (value)" separated by "," and the keyword string and value are separated by ":". The syntax structure is like code.


{
  key1:value1,
  key2:value2,
  ...
}

For example:


{
  "name": "hum",
  "age": 26,
  "sex": 1,
  "love": [
    "swing",
    "jump"
  ],
  "birthday": "1988-01-12"
}

NOTE:

It is best to enclose an JSON string in js with single quotation marks.

As follows:

console.log(JSON.parse('{"num":5,"stop":true,"str":"hello","empty":null}'));// object{num:5,stop:true,str:"hello",empty: null}

In contrast to js object literals, JSON objects have no variable declarations and no semicolon at the end.
Array structure begins with "[" and ends with "]". It is composed of 0 or more value lists separated by ",", and its syntax structure is like code.


[
  {
    key1:value1,
    key2:value2,
   ...
  }
]

For example:


[
 {
   "Id": 7,
  "Mentions": [
    {
     "Id": 5,
     "StatusId": 34,
     "CreatedDateTime":"\/Date(1310051914617+0100)\/",
     "Text":"Text",
     "UserName":"Username",
    "UserLocation":"UK",
    "UserLanguage":"en-GB",
     "IsCheckIn":"true"
   }
  ],
   "Checkins": 0,
   "HereNow": 0,
   "TimeStamp":"\/Date(1310051914639+0100)\/",
   "Venue": {
    "Id": 7,
    "FoursquareId":"cacbf3bd-f0aa-403d-9f9b-2056b4985ba1",
    "Name":"Venue Name"
   }
  },
  {
    "name":"hahahhahah",
    "port":[
     {
       "port": 8080,
       "protocol":"HTTP",
       "IP":"123.12.06.456"
     }
    ]
  }
]

The JSON array takes the literal form of the javascript array.

Parsing and Serialization of JSON

The parsing and serialization of JSON of js is the same as that of AS3. We commonly used is JSON object (ECMAScript 5 added, early JSON parsing basically use eval () function of javascript. But eval has some performance and security shortcomings, ECMAScript parsing JSON object specification, defined the global object JSON, supported browsers are standard browsers and IE8 +. For unsupported browsers can introduce json2.js file.) stringify and parse.

Next, let's explain 11.

JSON.stringify

JSON. stringify () serializes an javascript object into a string in JSON format
JSON. stringify (ob, filter, indent) contains three parameters, and we usually use it with only the first parameter to return a string.

ob: The object, array, raw value to convert to an JSON string.
filter: Is an optional argument, usually a function, to make a few substitutions for the value before stringization. It can also be an array containing which attribute names need to be stringed. Is used for filtering.
indent: Also an optional parameter that specifies the string or space to be indented when you want to output formatted readable code. If this parameter is omitted, the returned string will not have any extra spaces, making the output value difficult to read. Is used for formatting.

Here are a few corresponding examples:

First, when the second parameter is an array filter:


var oJson = { name: 'hum', age: 20, sex: 1};
console.log(JSON.stringify(oJson, ['age', 'sex'])); // {"age":20,"sex":1}

If the second argument is a string, the array will be used as the property name of the object, and the properties of any object whose property name is not in this array will be ignored during serialization. In addition, the order of the attributes in the returned string will correspond to the attribute name 1 in the array.

Function filter:


var oJson = { name: 'hum', age: 26, sex: 1, love: ['swing', 'jump']};
  console.log(JSON.stringify(oJson, function(k, v){
    switch (k){
      case 'age':
        return v > 20 ? ' Adulthood ': ' Minor ';
      case 'love':
        return v.join(',');
      case 'sex':
        return undefined;
      default :
        return v;
    }
  })); // {"name":"hum","age":" Adulthood ","love":"swing,jump"}

If the argument is a function, it is a substitution function that is called on every object that needs to be stringed. The first argument of this function is the property name or array ordinal number in the object, and the second is the value itself. The return value of the function replaces the value that needs to be stringed. If the function returns undefined or has no return value, this value will be ignored during stringization.

An example of the third parameter of stringify:


var oJson = { name: 'hum', age: 26, sex: 1, love: ['swing', 'jump']};
  console.log(JSON.stringify(oJson, null, 4));
  /*
   {
     "name": "hum",
     "age": 26,
     "sex": 1,
     "love": [
       "swing",
       "jump"
     ]
   }
  */

Usually the return value of this method is a machine-readable string without any spaces or newlines. If you want to output more readable code, you need to set the third parameter.

Let's look at another example:


var oJson = { name: 'hum', age: 26, sex: 1, love: ['swing', 'jump']};
  console.log(JSON.stringify(oJson, null, '--'));
  /*
   {
   --"name": "hum",
   --"age": 26,
   --"sex": 1,
   --"love": [
   ----"swing",
   ----"jump"
   --]
   }
  */

This makes it easy to understand. . .

JSON.parse

JSON. parse is used to parse a string in json format (returns 1 object, array, or raw value)

JSON. parse (s, reviver) contains two methods.

s: String to parse
reviver: Optional function for converting parse values

We usually use only the first parameter, optional parameter reviver, to filter or post-process the resolved value before returning it. The reviver function is called once for each original value parsed from s. The reviver function is called with two arguments, the first property name (the property name of the object or the array ordinal number converted to a string), and the second argument is the property of the object or the element value of the array. The reviver function is called as a method of an object/array containing the original value. The return value of the reviver function becomes the new value of the property, and if reviver returns the second parameter, the property remains unchanged. If reviver returns undefined or anything, the attribute is removed from the object or array.
Here is an example:


var oJson = { name: 'hum', age: 26, sex: 1, love: ['swing', 'jump'], birthday: '1988-01-12'};
  var sJson = JSON.stringify(oJson);
  console.log(sJson);//{"name":"hum","age":26,"sex":1,"love":["swing","jump"],"birthday":"1988-01-12"}
  console.log(JSON.parse(sJson));
  console.log(JSON.parse(sJson, function (k, v) {
    if(k == 'birthday'){ //  Returns a date object 
      return new Date(v);
    }else if(k == 'sex'){ // sex It's gone 
      return undefined;
    }else{
      return v;
    }
  }));

PS: Regarding json operation, here we recommend several practical json online tools for your reference:

Online JSON code verification, verification, beautification and formatting tools:
http://tools.ofstack.com/code/json

JSON Online Formatting Tool:
http://tools.ofstack.com/code/jsonformat

Online XML/JSON interconversion tool:
http://tools.ofstack.com/code/xmljson

json code online formatting/beautification/compression/editing/conversion tool:
http://tools.ofstack.com/code/jsoncodeformat

Online json compression/escape tool:
http://tools.ofstack.com/code/json_yasuo_trans

C Language Style/HTML/CSS/json Code Formatting and Beautification Tool:
http://tools.ofstack.com/code/ccode_html_css_json

For more information about JavaScript, please see the topics on this site: "Summary of json Operation Skills in JavaScript", "Summary of JavaScript Search Algorithm Skills", "Summary of JavaScript Error and Debugging Skills", "Summary of JavaScript Data Structure and Algorithm Skills", "Summary of JavaScript Traversal Algorithm and Skills" and "Summary of JavaScript Mathematical Operation Usage"

I hope this article is helpful to everyone's JavaScript programming.


Related articles: