JSON.stringify 和 JSON.parse 的实现

2017-08-25  本文已影响697人  McDu

1. JSON.stringify

JSON.stringify(value[, replacer [, space]])

关于序列化,有下面五点注意事项:

如何自己实现 JSON.stringify?
这里有一个 MDN 的 Polyfill,比较复杂,下面是另找的一段代码,做了一些改动,让type == 'undefined' || 'function' 的结果返回字符串,待优化。

 function myJsonStringify(obj) {
        let type = typeof obj;
        if (type !== "object" || type === null) {
            if (/string|undefined|function/.test(type)) {
                obj = '"' + obj + '"';
            }
            return String(obj);
        } else {
            let json = [],
                arr = (obj && obj.constructor === Array);

            for (let k in obj) {
                let v = obj[k];
                let type = typeof v;

                if (/string|undefined|function/.test(type)) {
                    v = '"' + v + '"';
                } else if (type === "object") {
                    v = myJsonStringify(v);
                }

                json.push((arr ? "" : '"' + k + '":') + String(v));
            }
            return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}")
        }
    }

找了一段“完美”的代码:

if (!window.JSON) {
    window.JSON = {
        parse: function(jsonStr) {
            return eval('(' + jsonStr + ')');
        },
        stringify: function(jsonObj) {
            var result = '',
                curVal;
            if (jsonObj === null) {
                return String(jsonObj);
            }
            switch (typeof jsonObj) {
                case 'number':
                case 'boolean':
                    return String(jsonObj);
                case 'string':
                    return '"' + jsonObj + '"';
                case 'undefined':
                case 'function':
                    return undefined;
            }

            switch (Object.prototype.toString.call(jsonObj)) {
                case '[object Array]':
                    result += '[';
                    for (var i = 0, len = jsonObj.length; i < len; i++) {
                        curVal = JSON.stringify(jsonObj[i]);
                        result += (curVal === undefined ? null : curVal) + ",";
                    }
                    if (result !== '[') {
                        result = result.slice(0, -1);
                    }
                    result += ']';
                    return result;
                case '[object Date]':
                    return '"' + (jsonObj.toJSON ? jsonObj.toJSON() : jsonObj.toString()) + '"';
                case '[object RegExp]':
                    return "{}";
                case '[object Object]':
                    result += '{';
                    for (i in jsonObj) {
                        if (jsonObj.hasOwnProperty(i)) {
                            curVal = JSON.stringify(jsonObj[i]);
                            if (curVal !== undefined) {
                                result += '"' + i + '":' + curVal + ',';
                            }
                        }
                    }
                    if (result !== '{') {
                        result = result.slice(0, -1);
                    }
                    result += '}';
                    return result;

                case '[object String]':
                    return '"' + jsonObj.toString() + '"';
                case '[object Number]':
                case '[object Boolean]':
                    return jsonObj.toString();
            }
        }
    };
}

使用 JSON.parse 解析自定义的 JSON 格式:

2. JSON.parse

JSON.parse() 方法解析一个JSON字符串,构造由字符串描述的JavaScript值或对象。可以提供可选的reviver函数以在返回之前对所得到的对象执行变换。

JSON.parse(text[, reviver])

 function jsonParse(opt) {
        return eval('(' + opt + ')');
    }

使用自定义的 jsonParse 解析 :

参考资料:

上一篇 下一篇

猜你喜欢

热点阅读