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.

What is serialization?

Types of serialization:

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().

How is Serialization used in code?

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.

Conclusion

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

JS Dev

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store