0

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.

5
  • 2
    Adding some justification why JSON.stringify is not an answer should help give you more useful answers. Commented Nov 17, 2014 at 7:04
  • Thanks for advise, I did it. Hope it will help. Commented Nov 17, 2014 at 7:11
  • 4
    Can you use this instead? Commented Nov 17, 2014 at 7:12
  • 1
    If you can inject your own code, you can inject Crockford's JSON2. Reinventing the wheel is rarely useful. Commented Nov 17, 2014 at 7:13
  • you can get a polyfill for the JSON objhect Commented Nov 17, 2014 at 7:36

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.