javascriptのtoString()


万能からのstackover flow分です.
 
var JSON = {};
JSON.stringify = JSON.stringify || function (obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string") obj = '"'+obj+'"';
        return String(obj);
    }
    else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n]; t = typeof(v);
            if (t == "string") v = '"'+v+'"';
            else if (t == "object" && v !== null) v = JSON.stringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};

var tmp = {one: 1, two: "2"};
console.log(JSON.stringify(tmp)); 
// '{"one":1,"two":"2"}'

var obj1 = {"name":"robin", location:{"city":"chengdu","desc":"javaer"}}
console.log(JSON.stringify(obj1)); 
// '{"name":"robin","location":{"city":"chengdu","desc":"javaer"}}'

var obj2 = {"name":"robin", location:{"city":"chengdu","job":{"titile":"jee","company":"cccc"}}}
console.log(JSON.stringify(obj2)); 
// '{"name":"robin","location":{"city":"chengdu","job":{"titile":"jee","company":"cccc"}}}'