Kalamarico Kalamarico - 1 year ago 98
JSON Question

serialize javascript object into 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:


The result is:

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

but i need that the typeof the objects includes in json string, like this:

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

There are a fast way using any framework or something? or i need to implement the toJson() method in the class and do it manually.


Answer Source

ok i resolve my problem in this way:

i adjust the json2.js standard method JSON.stringify() and in str() function when reads an object i put first the typeof, very simple:

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

Only to add is a classname attribute in my classes. And after the iterate adds this sentence:


// 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(",}", "}");

Thanks all.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download