Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to JSON.stringify a user-defined class in Javascript?

JSON.stringify() works on literal objects, such as:

var myObjectLiteral = {
    a : "1a",
    b : "1b",
    c : 100,
    d : {
        da : "1da",
        dc : 200
    }
};
var myObjectLiteralSerialized = JSON.stringify(myObjectLiteral); 

myObjectLiteralSerialized is assigned, "{"a":"1a","b":"1b","c":100,"d":{"da":"1da","dc":200}}" as expected.

But, if I define the class with a ctor like this,

    function MyClass() {
    var a = "1a";
    var b = "1b";
    var c = 100;
    var d = {
        da : "1da",
        dc : 200
    };
};


var myObject = new MyClass;
var myObjectSerialized = JSON.stringify(myObject);

then myObjectSerialized is set to the empty string, "".

I think the reason is because the class version ends up being the prototype of the instantiated class which makes it's properties "owned" by the prototype and JSON will only stringify props owned by the instance object, myObject.

Is there a simple way to get my classes into JSON strings w/o writing a bunch of custom code?

like image 642
Tom Jones Avatar asked Jan 21 '26 01:01

Tom Jones


1 Answers

Your MyClass isn't setting any properties on the object being constructed. It's just creating local variables to the constructor.

To create properties, set properties on this in the constructor, since this references the new object:

function MyClass() {
    this.a = "1a";
    this.b = "1b";
    this.c = 100;
    this.d = {
        da : "1da",
        dc : 200
    };
}

Also, you typically wouldn't add properties to the .prototype object inside the constructor. They only need to be added once, and will be shared among objects created from the constructor.

function MyClass() {
    this.a = "1a";
    this.b = "1b";
    this.c = 100;
    this.d = {
        da : "1da",
        dc : 200
    };
}

MyClass.prototype.toJSON = function() {
    return; // ???
}
MyClass.prototype.equals = function(other) {
    if(other != null && other.prototype == this) {
        if(this.a == other.a
            && this.b == other.b
            && this.c == other.c
            && this.d.da == other.d.da
            && this.d.dc == other.d.dc)
            return true;
    }
    return false;
}
like image 197
user113716 Avatar answered Jan 23 '26 13:01

user113716



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!