views:

26

answers:

1

I have written following function that takes json object and returns a serialized json String:

function serializeJson(object) {

    if(isArray(object)) {
        console.log("This is an array");
        return walkThrough(object);
    }
    else {
        console.log("This is an object");
        var key, value;
        var jsonArr = [];
        for(key in object) {
            value = object[key];
            if(typeof(value) == "string") {
                console.log("found a string " + key + " : " + value);

                jsonArr.push(key + " : '" + value + "'");
            }
            else if(typeof(value) == "object") {

                console.log("found an object with key " + key);
                if(isArray(value)) {
                    console.log("This is another array");
                    jsonArr.push(key + " : " + walkThrough(value));
                }
                else {
                    jsonArr.push(key + " : "+ serializeJson(value));
                }
            }
            else {
                jsonArr.push(key + " : " + value);
            }
        }
        return "{" + String(jsonArr) + "}";
    }
}

// called if an array is encountered
function walkThrough(ob) {
    var i=0;
    var jsonArr = [];
    var type = typeof(ob);
    for(;i<ob.length;i++) {
        if(typeof(ob[i]) == "string") {
            jsonArr.push("'" + ob[i] + "'");
        }
        else if (typeof(ob[i]) == "object") {
            if(isArray(ob[i])) {
                jsonArr.push(walkThrough(ob[i]));
            }
            else {
                jsonArr.push(serializeJson(ob[i]));
            }
        }
        else {
            jsonArr.push(ob[i]);
        }
    }
    return "[" + String(jsonArr) + "]";
}
function isArray(object) {

    if (object.constructor.toString().indexOf("Array") == -1)
        return false;
    else
        return true;
}

I do not see the function working as expected. My Json object is way too complex with so many nested objects and arrays. JSON.stringify() and dojo.toJson() fail and throw "too much recursion" error while trying to serialize! Is there no way to serialize a dojo tree data to a string?

Json object contains dojo tree data which I'm trying to serialize.

Is there an easier way to achieve this? Any inputs would be helpful. Thanks in advance!

A: 

This thread may help you.

Thariama