JavaScript Serializing JSON

In this tutorial we will learn how to serialize JavaScript objects to JSON.

Introduction

In this tutorial we will learn how to serialize JavaScript objects to JSON. Although the JSON format is based on the JavaScript object syntax, they are not the same [1]. So, it means that not all JavaScript objects can be fully serialized to JSON.

So, it makes sense to have a way of converting between the two formats: JSON and JavaScript objects. In this tutorial, as already mentioned, we will focus on converting JavaScript objects into JSON strings. This operation is called serialization.

The code

We will start by defining a very simple JavaScript object, representing some information about a person. It will have 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, we simply need to call the stringify method on the JSON object. Note that since JSON is a standard built in object [2], we don’t need to import it explicitly in our code.

As output, we get the JSON string representation of our JavaScript object, which we can directly printed to the console.

console.log(JSON.stringify(jsObject));

Upon running the code in a tool of your choice (I’m using Visual Studio Code with the Code Runner extension), you should get an output like shown in figure 1. As can be seen, we have obtained the correct JSON string representing our object.

To confirm we obtained a correctly formatted JSON string, we can use a online tool such as this.

Output of the program, showing the JSON string.
Figure 1 – Output of the program, showing the JSON string.

Note that the previous JSON string is obtained in a compacted format, ideal to be used for communication (less overhead with unnecessary characters). Nonetheless, if we want a pretty printed JSON in a more human readable format, we can make use of some additional parameters supported by the stringify method.

So, as second and optional parameter, this method can receive a replacer function that can alter the stringification process [3]. We are not making use of it on this tutorial, so it can be set as null.

As third and also optional parameter, we can pass a number that is used to insert white space in the resulting string, in order to make it more readable [3]. Note that this number should be between 1 and 10. Values greater than 10 will be interpreted as 10 [3].

We will be using a value of 3. So, 3 whitespaces should be inserted by indentation level of the JSON.

console.log(JSON.stringify(jsObject, null, 3));

As output, you should get a JSON string formatted like shown in figure 2. As can be seen, we have obtained a nicely formatted string that is easier to read. Nonetheless, it is not the optimal way of changing information between applications, since the additional white spaces are overhead that is not necessary for the JSON to be correctly deserialized.

Pretty printed JSON string.
Figure 2 – Pretty printed JSON string.

Take in consideration that functions are not valid JSON values [3]. This means they are going to be omitted in the serialized JSON (or changed to null, if found in an array) [3].

const objectWithFunction = {
  someProperty: "some value",
  func: () => console.log("test"),
  arrayOfFunctions: [
    () => console.log("test"), 
    () => console.log("test2")
  ]
}

console.log(JSON.stringify(objectWithFunction, null, 3));

If we run the previous code, we get the output shown in figure 3. As can be seen, the object property called func was not serialized and the functions inside the arrayOfFunctions array were replaced by the value null.

Output of the serialized object that contained functions.
Figure 3 – Output of the serialized object that contained functions.

References

[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON

[2] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects

[3] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Leave a Reply