genichm
genichm

Reputation: 535

Javascript object serialization function

I need a function that can serialize object of type {"a":"val", "b":{}, "c":[{}]} without JSON.stringify (cause the environment simply does not has JSON object) or using jquery and any other library. The code bellow is what I have at this moment:

function objToString(obj) {
    if (obj == null) return null;
    var index = 0;
    var str = '{';
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
            str += index != 0 ? "," : "";
            str += '"' + p + '":' + (typeof (obj[p]) == 'object' ? objToString(obj[p]) : itemToJsonItem(obj[p]));
            index++;
        }
    }
    str += "}";
    return str;
}

function itemToJsonItem(item) {
    return isNaN(item) ? '"' + item + '"' : item;
}

This function can deal with objects, nested objects but not with arrays. Node "c" from mentioned object will looks like "c":{"0":{...}} and not like array. Unsurprising "c".constructor === Array is false cause it interpreted as function and not as array. This is complete code where you can see what happens.

<div id="div_result"></div>

<script>
    var test = { "a": "val", "b": [{"c":"val c"}]};

    function objToString(obj) {
        if (obj == null) return null;
        var index = 0;
        var str = '{';
        for (var p in obj) {
            if (obj.hasOwnProperty(p)) {
                str += index != 0 ? "," : "";
                str += '"' + p + '":' + (typeof (obj[p]) == 'object' ? objToString(obj[p]) : itemToJsonItem(obj[p]));
                index++;
            }
        }
        str += "}";
        return str;
    }

    function itemToJsonItem(item) {
        return isNaN(item) ? '"' + item + '"' : item;
    }

    document.getElementById("div_result").innerHTML = objToString(test);
</script>

I will really appreciate help, at this moment serialized object created by toSerialize function inside of each object but we want to make it with outside standard function.

Upvotes: 0

Views: 91

Answers (1)

dizel3d
dizel3d

Reputation: 3669

Try to use JSON 3. It is polyfill library for window.JSON. It exposes JSON.stringify and JSON.parse methods.

Upvotes: 3

Related Questions