74

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?

SOLO
8789 silver badges19 bronze badges
asked Nov 17, 2011 at 9:26
0

9 Answers 9

89
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
}};
Paolo
21.4k21 gold badges78 silver badges124 bronze badges
answered Nov 17, 2011 at 9:30
Sign up to request clarification or add additional context in comments.

2 Comments

its a good idea, but not only have a class MyClass, inside MyClass i have a lot attributes that are objects, and i dont know it.
You could use myobject.constructor. See my answer or developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… for more info!
19

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}
SOLO
8789 silver badges19 bronze badges
answered Nov 21, 2014 at 6:22

Comments

2

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.

answered Nov 17, 2011 at 10:23

Comments

2

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.

answered Feb 27, 2013 at 4:55

2 Comments

HydrateJS appears to correctly handle both function serialisation and circular references. Not many libraries do! +1
Unfortunately, HydrateJS is also poorly documented and seemingly unmaintained
1

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.

answered Nov 17, 2011 at 9:54

Comments

1

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));
answered Nov 18, 2011 at 11:45

Comments

1
 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');*/ });
answered Jul 18, 2018 at 7:20

Comments

0

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));
answered May 22, 2019 at 14:00

Comments

0

Try json-stash. It lets you define a serializer for any object type.

const { stash, unstash, addSerializers } = require('json-stash');
const MyClass1 = function(id, member) {
 this.id = id;
 this.member = member;
}
const myobject = new MyClass1("5678999", "text");
// add a serializer for this object type
const serializer = {
 type: MyClass1,
 save: (obj) => [obj.id, obj.member],
};
addSerializers([serializer]);
console.log(stash(myobject));
// '{"$type":"MyClass1","data":["5678999","text"]}'
console.log(unstash(stash(myobject)));
// MyClass1 { id: '5678999', member: 'text' }
answered Mar 25, 2023 at 13:22

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.