1. JSON.stringify
JSON.stringify(value[, replacer [, space]])
關(guān)于序列化,有下面五點(diǎn)注意事項(xiàng):
- 非數(shù)組對象的屬性不能保證以特定的順序出現(xiàn)在序列化后的字符串中。
- 布爾值、數(shù)字、字符串的包裝對象在序列化過程中會(huì)自動(dòng)轉(zhuǎn)換成對應(yīng)的原始值。
- undefined、任意的函數(shù)以及 symbol 值,在序列化過程中會(huì)被忽略(出現(xiàn)在非數(shù)組對象的屬性值中時(shí))或者被轉(zhuǎn)換成 null(出現(xiàn)在數(shù)組中時(shí))。
- 所有以 symbol 為屬性鍵的屬性都會(huì)被完全忽略掉,即便 replacer 參數(shù)中強(qiáng)制指定包含了它們。
- 不可枚舉的屬性會(huì)被忽略
- 如果一個(gè)對象的屬性值通過某種間接的方式指回該對象本身,即循環(huán)引用,屬性也會(huì)被忽略


如何自己實(shí)現(xiàn) JSON.stringify?
這里有一個(gè) MDN 的 Polyfill,比較復(fù)雜,下面是另找的一段代碼,做了一些改動(dòng),讓type == 'undefined' || 'function' 的結(jié)果返回字符串,待優(yōu)化。
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() 方法解析一個(gè)JSON字符串,構(gòu)造由字符串描述的JavaScript值或?qū)ο???梢蕴峁┛蛇x的reviver函數(shù)以在返回之前對所得到的對象執(zhí)行變換。
JSON.parse(text[, reviver])
function jsonParse(opt) {
return eval('(' + opt + ')');
}
使用自定義的 jsonParse 解析 :

參考資料: