現代瀏覽器大多已原生支援 JSON.stringify,但在較舊的環境(比如那個經典的 IE6)裡就得自己動手。出發之前,先把標準行為摸清,實作才有對照組。
以下測試涵蓋了各種邊界情況,可以作為後續實作與驗證的基準:
function test_toStringify(){
var result = {
"JSON.stringify(undefined)": JSON.stringify(undefined),
"JSON.stringify(null)": JSON.stringify(null),
"JSON.stringify(123)": JSON.stringify(123),
"JSON.stringify(true)": JSON.stringify(true),
"JSON.stringify('')": JSON.stringify(''),
"JSON.stringify('abc')": JSON.stringify('abc'),
"JSON.stringify([1,2,3])": JSON.stringify([1,2,3]),
"JSON.stringify([undefined, undefined])": JSON.stringify([undefined, undefined]),
"JSON.stringify({name:'chyingp', age:24, u:undefined})":
JSON.stringify({name:'chyingp', age:24, u:undefined})
};
var str = '';
for(var key in result){
if(typeof result[key] === 'string'){
str += key + " : '" + result[key] + "'\n";
}else{
str += key + " : " + result[key] + "\n";
}
}
console.log(str);
}
輸出結果:
JSON.stringify(undefined) : undefined
JSON.stringify(null) : 'null'
JSON.stringify(123) : '123'
JSON.stringify(true) : 'true'
JSON.stringify('') : '""'
JSON.stringify('abc') : '"abc"'
JSON.stringify([1,2,3]) : '[1,2,3]'
JSON.stringify([undefined, undefined]) : '[null,null]'
JSON.stringify({name:'chyingp', age:24, u:undefined}) : '{"name":"chyingp","age":24}'
幾個關鍵規則由此可見:undefined 本身回傳 undefined(不是字串);陣列中的 undefined 會被替換成 null;物件中值為 undefined 的鍵會被整個省略。
型別判斷建議統一走 Object.prototype.toString.call(),這比 typeof 或 instanceof 都可靠:
function is_number(obj){ return Object.prototype.toString.call(obj) === '[object Number]'; }
function is_boolean(obj){ return Object.prototype.toString.call(obj) === '[object Boolean]'; }
function is_string(obj){ return Object.prototype.toString.call(obj) === '[object String]'; }
function is_null(obj){ return Object.prototype.toString.call(obj) === '[object Null]'; }
function is_undefined(obj){ return Object.prototype.toString.call(obj) === '[object Undefined]'; }
function is_object(obj){ return Object.prototype.toString.call(obj) === '[object Object]'; }
function is_array(obj){ return Object.prototype.toString.call(obj) === '[object Array]'; }
function is_function(obj){ return Object.prototype.toString.call(obj) === '[object Function]'; }
function quote(str){ return '"' + str + '"'; }
var basic_map = {
'[object Undefined]': true,
'[object Number]': true,
'[object Null]': true,
'[object Boolean]': true
};
function basic_type(obj){ return basic_map[ Object.prototype.toString.call(obj) ]; }
JSON = window.JSON || {};
// 本質上就是 JSON.stringify
JSON.toStr = function(obj){
if(is_string(obj) || is_null(obj) || is_number(obj) || is_boolean(obj)) return quote(obj);
if(is_undefined(obj)) return obj;
if(is_array(obj)){
var left = "[", middle = [], right = "]", value;
var callee = arguments.callee;
for(var i = 0, len = obj.length; i < len; i++){
var value = obj[i];
if( typeof value === 'undefined' ){
middle.push(null + '');
}else{
if( basic_type(value) ){
middle.push( value );
}else{
middle.push( callee(obj[i]) );
}
}
}
return left + middle.join(",") + right;
}
if(is_object(obj)){
var left = "{", middle = [], right = "}", value;
var callee = arguments.callee;
for(var key in obj){
var value = obj[key];
if(typeof obj[key] === 'undefined') continue; // 與標準一致:跳過 undefined 鍵
if( basic_type(value) ){
middle.push( quote(key) + ':' + value );
}else{
middle.push( quote(key) + ':' + callee(value) );
}
}
return left + middle.join(', ') + right;
}
};
!JSON.stringify && (JSON.stringify = JSON.toStr);
這份實作用 arguments.callee 做遞迴,重點是展示原理,並非追求效能的最優解。若要在正式環境使用,建議直接引入成熟的 polyfill 或 json2.js,它處理了字串轉義、巢狀深度、toJSON 鉤子等本文未涵蓋的細節。
關於 JSON 操作,這裡一併整理幾個線上工具: