The Deal With Serialization in Javascript

In Javascript, data can be transferred from one machine to another using a process known as serialization. Today I will be diving into what serialization is, what the different methods are, and how it can be used in your code. Let’s get started.

Serialization, in short, is the process in which a data structure or object can be translated into raw data suitable for any device, and transmitted to a remote machine or network where the data can be parsed, and collected.

JSON: Converts objects/data into strings for transmitting data to another remote machine or network. JSON strings after transmission can be “parsed” in order to convert the received string into data again. Methods include JSON.stringify(), and JSON.parse().

XML-serializer: Is a class which converts DOM trees into strings which contain XML. XML strings could then be “parsed” into DOM trees, returning XML documents/documents based on input data. Methods include XMLSerializer(), and DOMParser().

CSV: A Javascript library meant for fetching data from files/HTTP requests and converting data into a string in a CSV format or parsing CSV strings back into CSV files after data transmission. Methods include CSV.fetch().

Buffer: A NodeJS feature which allows for transmitting data from files and bringing data into another file in raw buffer data. This data could then be translated into any format(preferably a string). Methods include buffer.toString().

For the sake of this article, I will be demonstrating examples of serialization using JSON methods.

So let’s say for example that we wanted to send to a server an object called “bankAccounts” with two key value pairs, one which holds the total number of accounts, and the other which acts as storage for each name and balance.

Now if we were to execute this code above at run-time, below will be the result.

This result, however, cannot be transmitted across remote machines in the current format. In this case, the solution would be to use the JSON.stringify() method to convert the script data into a string for transmission.

Now that we have the data converted into a string, it is ready to be sent to another machine. So let’s say we sent this stringified data to a server and the server sent the data to a remote machine. This is where we use the reversal method, JSON.parse(), to deserialize the serialized data back into a datatype/object.

We could then use the data we sent from one machine on another machine on run-time.

Serialization is the process in which datatypes/objects can be translated into raw data (or bytes) and can be transmitted to remote machines or saved on hard disks.

Deserialization is the process in which raw data is then reverted into the original datatypes/objects that they were for future use.

JS Dev

JS Dev