基本上我有这样的东西:
我的类(class)
var MyClass = function() {
this.num = 123;
this.obj = new MyInnerClass();
};
MyClass.prototype.stringify = function() {
return JSON.stringify(this);
};
我的内部类
var MyInnerClass = function() {
this.foo = 456;
this.bar = 'bonjour!';
};
MyInnerClass.prototype.stringify = function() {
return JSON.stringify(this, function(k, v) {
// ignores 'foo' attribute
return k !== 'foo' ? v : undefined;
});
};
每个类都有自己的stringify
实现,所以当我这样做时:
var mc = new MyClass();
mc.stringify();
我想要像调用MyClass.stringify
这样的东西来字符串化我的mc
对象,但尊重内部对象stringify
实现。一旦我们无法控制 JSON.stringify
方法逻辑,是否有好的方法来做到这一点?
谢谢!
最佳答案
如果您查看 MDN 的 JSON.stringify,您会看到一个讨论 toJSON 属性的部分
If an object being stringified has a property named toJSON whose value is a function, then the toJSON() method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON() method when called will be serialized.
基本上,为您的对象定义一个toJSON方法,该方法创建另一个对象,但可以根据您的需要进行序列化。然后 JSON.stringify
将序列化 toJSON
函数的返回,即
var MyClass = function() {
this.num = 123;
this.obj = new MyInnerClass();
};
var MyInnerClass = function() {
this.foo = 456;
this.bar = 'bonjour!';
};
MyInnerClass.prototype.toJSON = function () {
// shallow clone `this`, except .foo
var o = Object.create(null), k, blacklist = ['foo'];
for (k in this) // loop over enumerable properties
if (Object.prototype.hasOwnProperty.call(this, k)) // ignore inherited properties
if (blacklist.indexOf(k) === -1) // ignore blacklisted properties
o[k] = this[k]; // add to our clone
return o;
};
JSON.stringify(new MyClass()); // '{"num":123,"obj":{"bar":"bonjour!"}}'
这也将取代您对当前 stringify 方法的需求。
<小时/>遗憾的是,您无法在 .toJSON
中调用 JSON.stringify(this)
,因为它会变成循环,并且您会收到 RangeError: Maximum call stack size gone
,但无论如何您都不会以这种方式获得所需的结果,因为它会被第二次序列化,从而在 JSON 中为您提供一个 String。
关于javascript - 字符串化 JSON 内部对象的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31190525/