首页 > JSON.stringify({a:1,b:2,c:undefined})如何不忽略c

JSON.stringify({a:1,b:2,c:undefined})如何不忽略c


JSON.stringify({a:1,b:2,c:undefined});//'{"a":1,"b":2}'
如何JSON.stringify({a:1,b:2,c:undefined});//'{"a":1,"b":2,"c":""}'   

重新定义 undefined 使之成为 ""
因为重新定义全局 undefined 可能引起其它问题,所以需要封装在一个函数范围内

var s = (function() {
    var undefined = "";
    return JSON.stringify({a:1,b:2,c:undefined});
})();

// {"a":1,"b":2,"c":""}

http://stackoverflow.com/questions/26540706/json-stringify-removes-hash-keys-with-undefined-values


function setProp(obj) {
    for (var p in obj) {
        switch (typeof (obj[p])) {
            case 'object':
                setProp(obj[p]);
                break;
            case 'undefined':
                obj[p] = '';
                break;
        }
    }
    return obj;
}

JSON.stringify(setProp({ a: 1, b: 2, c: undefined }));
【热门文章】
【热门文章】