How to serialize an object in JavaScript?

For example, I have a class:

function Test() { } Test.prototype = { 'setTest' : function(test) { this.test = test; } } var test = new Test(); Test.setTest('test'); 

I want to save a test of an object in a database. How to serialize object check on string? (methods, variables, etc.)

+8
source share
6 answers

Simple with json

 JSON.stringify( test ); 
+10
source

In this case, there really is no way for the question you ask to do what you want. The problem with your request is "serializing everything related to the object, including functions".

Serialization usually occurs only for data, since executable files are usually linked by a machine, because they are compiled for a given machine based on certain characteristics. Now it’s wise to say that javascript functions just require a javascript interpreter because javascript is the one and only one that works everywhere. But when people write serializers, because all serializers tend to work the same way, we only write them for data. In this case, the industry standard is JSON, which is a serializer for object data only.

Currently there are three solutions available to you:

  • Create your own serializer / deserializer that encapsulates functions. This can be tricky because not all javascript engines will give you access to the source.
  • Write your own reload mechanism, which generates a specific new initialized type for each restore and saves the type name as one of the properties during serialization. Thus, initializing each variable gives you methods, and then merging with the data gives you a complete object.
  • Store each function as a string and evaluate it on the go as you need. This is incredibly complicated and it is quite error prone. I can not think of a single case when it becomes useful, because it is quite fragile. However, this is an option and cannot be ignored.

I know that 3 is a sub-answer for 1, so you can assume that there are only two useful answers.

I know that this works superficially on Chrome and IE9, so it should work everywhere, most users will most likely use it:

 var abc = function(thing) { return thing; } abc.toString(); // gives "function(thing) { return thing; }" on the command line 

This way you can serialize methods as strings instead of the actual method, but you will need to create a duplicate object so that you can capture every element of the original object (I think, instead of replacing them in place).

Hope this helps you think a little bit about the problem and perhaps realize that you don't need to serialize the methods (no one ever does what I know is not wise).

+8
source

The best way to do this is to write your own serialization method, which creates a JSON object with attributes based on your receiving methods. Usually you define a getter for each attribute. So this should work in most cases (so you don't need to define a serialization method for each class).

 function serialize(obj) { var serialized = {}; for(var prop in obj) { if (obj.hasOwnProperty(prop) && typeof obj[prop] == 'function') { if (/^get.*/.test(prop)) { var value = obj[prop](); var name = prop.replace('get', ''); if (typeof value === 'object') { serialized[name] = this.serialize(value); continue; } serialized[name] = value; } } } return serialized; }; 

To return attribute values ​​back to the class, you have two options:

  • Create a function in your class that creates a valid instance of the object based on serialized JSON.
  • Create an unserialize method and map the JSON to your class using installers.

Example:

 function unserialize(obj, emptyClass) { // Check emptyClass for setters and map the data from obj to it. return 'class instance'; } 
+3
source

Typically, you do this with JSON , which is widely supported in browsers / languages ​​/ libraries, etc. The only hover is that JSON does not support functions, but do you really need to serialize them?

+1
source

I had to maintain functionality similar to the previous one. I ended up saving the function name as a string and serializing it as JSON. Then, when I return to the client, I execute the function using an assistant similar to the one that was sent to this question .

If anyone has a better way to solve this problem, I would love to see him!

0
source

Recently I had to find a solution to this problem. I am sure that it can be improved.

First, I created a module to instantiate the "serialisable" object.

 function MyObj(serialised){ this.val = ""; if(serialised){ var unserialised = JSON.parse(serialised); for (var i in unserialised) { this[i] = unserialised[i]; } } } MyObj.prototype.myMethod = function () { return this.val;}; module.exports = MyObj; 

Of course, you should consider error handling and other checks.

-1
source

Source: https://habr.com/ru/post/921848/


All Articles