Javascript Serializer

Serialize Javascript variables


Introduction

Javascript Serializer can convert almost any object in a browser to a string representation of itself. It's useful when generating error logs when stack traces are not enough.

What This Tutorial Covers

What This Tutorial Covers
  1. Using Javascript Serializer
  2. What It Can't Serialize

What You Need For This Tutorial

What You Need For This Tutorial

A browser


Using Javascript Serializer

Javascript Serializer

To use Javascript Serializer, import the following two files:


<script src="https://cdn.rawgit.com/efossas/Javascript-Serializer/ca583a1e/serialize.min.js"><script>
<script src="https://cdn.rawgit.com/efossas/Javascript-Serializer/ca583a1e/deserialize.min.js"><script>
      

Using the serialize function couldn't be easier. You just pass the variable you want serialized into the function and it returns a string representation of the variable.


var myObject = { 'example' : 'object' };
var serializedObject = serialize(myObject);

// you can deserialize the string as well:
var deserializedObject = deserialize(serializedObject);
        

Caveats. What It Won't Serialize

In order to serialize an object, you need one of three things:

  1. If it's a primitive value, simple, you just store it as a string. To keep typing, you store primitive strings with single quotes around them.
  2. If it's an object, hopefully there is a reflection method that gives you a string that can help you reconstruct it.
  3. If it doesn't have reflection, but it's iterable, you can copy the object to a string by iterating through it.

You can see below, how the serialize function works, looking for one of those three conditions. However, it uses an additional trick. If it detects a native function (which is a built in function attached to the window), it will try to find it's name on the window. Since those native functions always exist on the window, if we can figure out the name, we can just leave it there, since it will resolve to native function when deserialized. You might think that should be easy, but there is no way of determining the name of a variable using javascript. For that matter, the variable name may have been changed and what we really want, is it's original property name on the window.

So what can't it serialize? An object that doesn't meet one of those 3 conditions and isn't a native function. Thus, a variable that is not a primitive, doesn't have a useful reflection method, and isn't iterable. An example of that is a Promise or pretty much any DOM object like the document, which is built using the HTMLDocument function object.

Done!

I hope you found that interesting if not useful.