Introduction

This article describes how to serialize JavaScript objects to JSON. Although the JSON format is based on the syntax of JavaScript objects, they are not the same, which means that not all JavaScript objects can be fully converted to JSON.

code example

Let's first define a simple JS object to represent information about a person. This object has the following fields:

  • name – a string;
  • age – a number;
  • birthDate – a date;
  • languages – an array of strings.
 const jsObject = {
  name: "Todd",
  age: 20,
  birthDate: new Date(),
  languages: ["Chinese", "English"]
}

To convert this object to a JSON string, just call the stringify method of the JSON object. Note that JSON is a standard built-in object and does not need to be introduced in the code.

 console.log(JSON.stringify(jsObject));
// {"name":"Todd","age":20,"birthDate":"2022-06-06T05:54:49.460Z","languages":["Chinese","English"]}

The result of serialization is a compressed format that is less expensive to transmit over the network because it has no unnecessary characters. If we want a more readable form of output, we can use some extra parameters supported by the stringify method.

JSON.stringify(jsObject, null, 3)

This method can receive three parameters. The second parameter is an optional parameter replacer function, which can change the processing process. We do not need to pass null here.

The third parameter is also optional, accepting a number as the number of whitespace characters inserted into the result can make the result more readable. It should be noted that the value range is between 1-10, and if it is greater than 10, it will default to 10.

 console.log(JSON.stringify(jsObject, null, 3));
/*
{
   "name": "Todd",
   "age": 20,
   "birthDate": "2022-06-06T05:54:49.460Z",
   "languages": [
      "Chinese",
      "English"
   ]
}
*/

function is not a valid JSON value, which means that it will be omitted during serialization, and will be converted to null if it is in an array

 const objectWithFunction = {
  someProperty: "some value",
  func: () => console.log("test"),
  arrayOfFunctions: [
    () => console.log("test"), 
    () => console.log("test2")
  ]
}
 
console.log(JSON.stringify(objectWithFunction, null, 3));
/*
{
   "someProperty": "some value",
   "arrayOfFunctions": [
      null,
      null
   ]
}
*/

来了老弟
508 声望31 粉丝

纸上得来终觉浅,绝知此事要躬行


引用和评论

0 条评论