javascript - 字符串化 JSON 内部对象的最佳实践

标签 javascript json node.js stringify

基本上我有这样的东西:

我的类(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/

相关文章:

java - 从 JSON 中提取值时遇到问题

javascript - 返回的数组打印数组索引而不是值

javascript - 在 Mongoose 中,找不到模块 '\node_modules\ipaddr.js\lib\ipaddr.js' 。请验证 package.json 是否具有有效的 "main"条目

javascript - 如何避免重复调用javascript函数

javascript - 正则表达式操作从字符串中替换动态单词/值

c# - socket.io 使用 Newtonsoft.json 和 socketIOClient 发送到 C#

json - Powershell:l 解析嵌套的 JSON

Javascript:将数组转换为 CSV 格式并复制到剪贴板

javascript - 在重复的 jQuery/Ajax 函数中设置延迟

node.js - 你如何修改 generator-angular-fullstack 图标?