如何将继承的对象字符串化为JSON? [英] How to stringify inherited objects to JSON?

查看:158
本文介绍了如何将继承的对象字符串化为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

json2.js在使用JSON.stringify()时似乎忽略了父对象的成员。示例:

json2.js seems to ignore members of the parent object when using JSON.stringify(). Example:

require('./json2.js');

function WorldObject(type) {    
    this.position = 4;
}

function Actor(val) {
    this.someVal = 50;
}

Actor.prototype = new WorldObject();

var a = new Actor(2);

console.log(a.position);
console.log(JSON.stringify(a));

输出为:

4
{"someVal":50}

我会期待此输出:

4
{"position":0, "someVal":50}


推荐答案

嗯,就是这样, JSON .stringify 不保留对象的任何非拥有属性。您可以在此处查看有关其他缺点和可能的解决方法的有趣讨论。

Well that's just the way it is, JSON.stringify does not preserve any of the not-owned properties of the object. You can have a look at an interesting discussion about other drawbacks and possible workarounds here.

另请注意,作者不仅记录了问题,还编写了一个名为 HydrateJS 可能会对你有所帮助。

Also note that the author has not only documented the problems, but also written a library called HydrateJS that might help you.

这个问题比第一眼看上去更深一些。即使 a 真的会字符串化为 {position:0,someVal:50} ,然后解析它稍后会创建一个具有所需属性的对象,但既不是Actor的实例,也不是WorldObject的原型链接(毕竟,解析方法没有这个信息,所以它不可能恢复它那样)。

The problem is a little bit deeper than it seems at the first sight. Even if a would really stringify to {"position":0, "someVal":50}, then parsing it later would create an object that has the desired properties, but is neither an instance of Actor, nor has it a prototype link to the WorldObject (after all, the parse method doesn't have this info, so it can't possibly restore it that way).

为了保留原型链,需要巧妙的技巧(比如HydrateJS中使用的那些)。如果这不是您的目标,也许您只需要在对其进行字符串化之前展平该对象。要做到这一点,你可以例如迭代对象的所有属性,无论它们是否属于它们并重新分配它们(这将确保它们在对象本身上定义而不是仅仅从原型继承)。

To preserve the prototype chain, clever tricks are necessary (like those used in HydrateJS). If this is not what you are aiming for, maybe you just need to "flatten" the object before stringifying it. To do that, you could e.g. iterate all the properties of the object, regardless of whether they are own or not and re-assign them (this will ensure they get defined on the object itself instead of just inherited from the prototype).

function flatten(obj) {
    var result = Object.create(obj);
    for(var key in result) {
        result[key] = result[key];
    }
    return result;
}

写入函数的方式不会改变原始对象。所以使用

The way the function is written it doesn't mutate the original object. So using

console.log(JSON.stringify(flatten(a)));

你会得到你想要的输出和 a 将保持不变。

you'll get the output you want and a will stay the same.

这篇关于如何将继承的对象字符串化为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆