前言
这是一道笔试题,要求模拟实现JSON.stringiry 的格式化输出,按照层级缩进,输出易读格式,即完成以下方法
JSON.stringify(jsObj, null, 4); // 缩进4个空格
如输入:
{a:1,b:[{bb:1},{bb:2}],c:"cc"}
字符打印结果:
{ "a": 1, "b": [ { "bb": 1 }, { "bb": 2 } ], "c": "cc" }
具体实现:
1 function isArray(obj) { 2 if (Array.isArray) { 3 return Array.isArray(obj); 4 } else { 5 return Object.prototype.toString.call(obj) == "[object Array]"; 6 } 7 } 8 9 function isObject(obj) { 10 return Object.prototype.toString.call(obj) == "[object Object]"; 11 } 12 13 function isString(obj) { 14 return typeof obj == "string"; 15 } 16 17 function isNull(obj) { 18 return typeof obj == "null"; 19 } 20 21 22 23 function processValue(value) { 24 if (!isString(value)) { 25 if (!isNull(value)) { 26 return value.toString(); // 针对Number和Boolean 27 } else { 28 return null; 29 } 30 } else { 31 return '"' + value.toString() + '"'; 32 } 33 } 34 35 function jsonStringify(value, indent) { 36 37 var indent = indent || ""; 38 var ret = indent + "{ "; 39 indent += " "; 40 var keys = Object.keys(value); 41 for (var i = 0; i < keys.length; i++) { 42 var key = keys[i]; 43 var v = value[key]; 44 ret += (indent + processValue(key) + ":"); 45 if (!isArray(v) || isObject(v)) { 46 ret += processValue(v); 47 } else { 48 var ind = indent + " "; 49 for (var k = 0; k < key.length; k++) { 50 ind += " "; 51 } 52 if (isArray(v)) { 53 ret += "[ "; 54 for (var j = 0; j < v.length; j++) { 55 ret += jsonStringify(v[j], ind); 56 if (j == v.length - 1) { 57 ret += " "; 58 } else { 59 ret += ", "; 60 } 61 } 62 ret += indent + ']'; 63 } else if (isObject(v)) { 64 ret += jsonStringify(v, ind); 65 } 66 } 67 68 if (i == keys.length - 1) { 69 ret += " " 70 } else { 71 ret += ", " 72 } 73 } 74 75 ret += indent.slice(4) + "}"; 76 return ret; 77 } 78 79 80 81 var result = jsonStringify({ 82 a: 1, 83 b: [{ 84 bb: 1 85 }, { 86 bb: 2 87 }], 88 c: "cc" 89 }); 90 console.log(result);