Serializing a JavaScript Object to a JSON String

I have this JavaScript prototype:

Utils.MyClass1 = function(id, member) { this.id = id; this.member = member; } 

and I create a new object:

 var myobject = new MyClass1("5678999", "text"); 

If I do:

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

result:

 {"id":"5678999", "member":"text"} 

but I need the object type to be included in the JSON string, for example:

 "MyClass1": { "id":"5678999", "member":"text"} 

Is there a quick way to do this with a framework or something? Or do I need to implement the toJson() method in the class and do it manually?

+53
json javascript constructor
Nov 17 '11 at 9:26 a.m.
source share
9 answers
 var myobject = new MyClass1("5678999", "text"); var dto = { MyClass1: myobject }; console.log(JSON.stringify(dto)); 

EDIT:

JSON.stringify will match all the "properties" of your class. If you want to save only some of them, you can specify them individually, for example like this:

 var dto = { MyClass1: { property1: myobject.property1, property2: myobject.property2 }}; 
+67
Nov 17 '11 at 9:30
source share

Is it just JSON? You can stringify() JSON:

 var obj = { cons: [[String, 'some', 'somemore']], func: function(param, param2){ param2.some = 'bla'; } }; var text = JSON.stringify(obj); 

And again, parse back to JSON using parse() :

 var myVar = JSON.parse(text); 

If you have functions in the object, use this to serialize:

 function objToString(obj, ndeep) { switch(typeof obj){ case "string": return '"'+obj+'"'; case "function": return obj.name || obj.toString(); case "object": var indent = Array(ndeep||1).join('\t'), isArray = Array.isArray(obj); return ('{['[+isArray] + Object.keys(obj).map(function(key){ return '\n\t' + indent +(isArray?'': key + ': ' )+ objToString(obj[key], (ndeep||1)+1); }).join(',') + '\n' + indent + '}]'[+isArray]).replace(/[\s\t\n]+(?=(?:[^\'"]*[\'"][^\'"]*[\'"])*[^\'"]*$)/g,''); default: return obj.toString(); } } 

Examples:

Serialization:

 var text = objToString(obj); //To Serialize Object 

Result:

 "{cons:[[String,"some","somemore"]],func:function(param,param2){param2.some='bla';}}" 

Deserialize:

 Var myObj = eval('('+text+')');//To UnSerialize 

Result:

 Object {cons: Array[1], func: function, spoof: function} 
+12
Nov 21 '14 at 6:22
source share

Well, the item type is not standard serialized, so you have to add it manually. for example

 var myobject = new MyClass1("5678999", "text"); var toJSONobject = { objectType: myobject.constructor, objectProperties: myobject }; console.log(JSON.stringify(toJSONobject)); 

Good luck

edit: changed typeof to the correct .constructor. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor for more information on the constructor property for objects.

+2
Nov 17 '11 at 10:23
source share

This may be helpful. http://nanodeath.github.com/HydrateJS/ https://github.com/nanodeath/HydrateJS

Use hydrate.stringify to serialize the object and hydrate.parse to deserialize.

+2
Feb 27 '13 at 4:55
source share

You can use a named function in the constructor.

 MyClass1 = function foo(id, member) { this.id = id; this.member = member; } var myobject = new MyClass1("5678999", "text"); console.log( myobject.constructor ); //function foo(id, member) { // this.id = id; // this.member = member; //} 

You can use the regular expression to parse "foo" from myobject.constructor and use it to get the name.

+1
Nov 17 2018-11-11T00:
source share

Below is another way that we can use JSON data with the JSON.stringify () function

 var Utils = {}; Utils.MyClass1 = function (id, member) { this.id = id; this.member = member; } var myobject = { MyClass1: new Utils.MyClass1("5678999", "text") }; alert(JSON.stringify(myobject)); 
+1
Nov 18 '11 at 11:45
source share
  function ArrayToObject( arr ) { var obj = {}; for (var i = 0; i < arr.length; ++i){ var name = arr[i].name; var value = arr[i].value; obj[name] = arr[i].value; } return obj; } var form_data = $('#my_form').serializeArray(); form_data = ArrayToObject( form_data ); form_data.action = event.target.id; form_data.target = event.target.dataset.event; console.log( form_data ); $.post("/api/v1/control/", form_data, function( response ){ console.log(response); }).done(function( response ) { $('#message_box').html('SUCCESS'); }) .fail(function( ) { $('#message_box').html('FAIL'); }) .always(function( ) { /*$('#message_box').html('SUCCESS');*/ }); 
+1
Jul 18 '18 at 7:20
source share

I solved my problem this way, but not in the best way, but interesting to share:

I directly changed the json2.js library (opposite to the best practices ...), changed the JSON.stringify () method and in the str () function when I read the object that I first set typeof:

 // Otherwise, iterate through all of the keys in the object. // I have introduced speechModify variable. var speechModify = false; if(value.classname) { partial.push('"' + value.classname + '":{'); speechModify = true; } 

This is just to add the classname attribute to my classes. And after iteration it adds the following sentence:

 if(speechModify) partial.push("}"); // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; v = v.replace("{,","{"); v = v.replace(",}", "}"); 
0
Nov 18 '11 at 13:10
source share

I had some problems using the above solutions with an object of type "associative array". These solutions seem to preserve values, but they do not preserve the actual names of the objects that these values ​​are associated with, which may cause some problems. So I put together the following functions, which I use instead:

 function flattenAssocArr(object) { if(typeof object == "object") { var keys = []; keys[0] = "ASSOCARR"; keys.push(...Object.keys(object)); var outArr = []; outArr[0] = keys; for(var i = 1; i < keys.length; i++) { outArr[i] = flattenAssocArr(object[keys[i]]) } return outArr; } else { return object; } } function expandAssocArr(object) { if(typeof object !== "object") return object; var keys = object[0]; var newObj = new Object(); if(keys[0] === "ASSOCARR") { for(var i = 1; i < keys.length; i++) { newObj[keys[i]] = expandAssocArr(object[i]) } } return newObj; } 

Please note that they cannot be used with any arbitrary object - basically it creates a new array, stores the keys as element 0 with the data following it. Therefore, if you try to load an array that is not created with these functions that have element 0 as a list of keys, the results may be ... interesting :)

I use it like this:

 var objAsString = JSON.stringify(flattenAssocArr(globalDataset)); var strAsObject = expandAssocArr(JSON.parse(objAsString)); 
0
May 22 '19 at 14:00
source share