这是一个尊重内置JSON.stringify()
规则同时也限制深度的函数:
function stringify(val, depth, replacer, space) {
depth = isNaN(+depth) ? 1 : depth;
function _build(key, val, depth, o, a) { // (JSON.stringify() has it's own rules, which we respect here by using it for property iteration)
return !val || typeof val != 'object' ? val : (a=Array.isArray(val), JSON.stringify(val, function(k,v){ if (a || depth > 0) { if (replacer) v=replacer(k,v); if (!k) return (a=Array.isArray(v),val=v); !o && (o=a?[]:{}); o[k] = _build(k, v, a?depth:depth-1); } }), o||(a?[]:{}));
}
return JSON.stringify(_build('', val, depth), null, space);
}
这个怎么运作:
_build()
递归调用以将嵌套对象和数组构建到请求的深度。JSON.stringify()
用于迭代每个对象的直接属性以遵守内置规则。'undefined' 总是从内部替换器返回,因此实际上还没有构造任何 JSON。请记住,第一次调用内部替换器时,键是空的(这是要字符串化的项目)。
JSON.stringify()
在最终结果上调用以生成实际的 JSON。
例子:
var value={a:[12,2,{y:3,z:{q:1}}],s:'!',o:{x:1,o2:{y:1}}};
console.log(stringify(value, 0, null, 2));
console.log(stringify(value, 1, null, 2));
console.log(stringify(value, 2, null, 2));
{}
{
"a": [
12,
2,
{}
],
"s": "!",
"o": {}
}
{
"a": [
12,
2,
{
"y": 3,
"z": {}
}
],
"s": "!",
"o": {
"x": 1,
"o2": {}
}
}
(有关处理循环引用的版本,请参见此处:https : //stackoverflow.com/a/57193345/1236397 - 包括 TypeScript 版本)
更新:修复了空数组呈现为空对象的错误。