Serialize JavaScript object into JSON string

JavascriptJsonConstructor

Javascript Problem Overview


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));

the result is:

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

but I need for the type of the objects to be included in the JSON string, like this:

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

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

Javascript Solutions


Solution 1 - Javascript

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

EDIT:

JSON.stringify will stringify all 'properties' of your class. If you want to persist only some of them, you can specify them individually like this:

var dto = { MyClass1: {
    property1: myobject.property1,
    property2: myobject.property2
}};

Solution 2 - Javascript

It's 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 parse back to JSON again with 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:

Serialize:

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}

Solution 3 - Javascript

Well, the type of an element is not standardly serialized, so you should 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.

Solution 4 - Javascript

This might be useful. http://nanodeath.github.com/HydrateJS/ https://github.com/nanodeath/HydrateJS

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

Solution 5 - Javascript

You can use a named function on 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 could use a regex to parse out 'foo' from myobject.constructor and use that to get the name.

Solution 6 - Javascript

Below is another way by which we can JSON data with 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));

Solution 7 - Javascript

    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');*/ });

Solution 8 - Javascript

I was having some issues using the above solutions with an "associative array" type object. These solutions seem to preserve the values, but they do not preserve the actual names of the objects that those values are associated with, which can cause some issues. So I put together the following functions which I am using 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;
}

Note that these can't be used with any arbitrary object -- basically it creates a new array, stores the keys as element 0, with the data following it. So if you try to load an array that isn't created with these functions having element 0 as a key list, the results might be...interesting :)

I'm using it like this:

var objAsString = JSON.stringify(flattenAssocArr(globalDataset));
var strAsObject = expandAssocArr(JSON.parse(objAsString));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKalamaricoView Question on Stackoverflow
Solution 1 - JavascriptJakub KoneckiView Answer on Stackoverflow
Solution 2 - JavascriptMSSView Answer on Stackoverflow
Solution 3 - JavascriptWillem MulderView Answer on Stackoverflow
Solution 4 - JavascriptdipsView Answer on Stackoverflow
Solution 5 - JavascriptGeuisView Answer on Stackoverflow
Solution 6 - JavascriptElias HossainView Answer on Stackoverflow
Solution 7 - JavascriptРоман ЗыковView Answer on Stackoverflow
Solution 8 - Javascripturza9814View Answer on Stackoverflow