javascript ES6 中有类似 object.toJSON 的东西吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32332196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:07:17  来源:igfitidea点击:

Is there something like object.toJSON in ES6?

javascriptecmascript-6babeljs

提问by Hedge

I'm using ES6 I transpile using Babel into ordinary JavaScript.

我使用的是 ES6,我使用 Babel 将其转换为普通的 JavaScript。

I want to serialise objects into JSON format and am wondering if ES5,ES6 offers a convenient function to do so.

我想将对象序列化为 JSON 格式,并且想知道 ES5、ES6 是否提供了一个方便的函数来这样做。

For Mapsand Setsthere is a toJSON()-function proposed in ES7

对于MapsSets有一个toJSON()在ES7建议-功能

回答by lxg

You can use JSON.stringifyand pass any kind of variable to it (given that it can be represented in JSON).

您可以使用JSON.stringify任何类型的变量并将其传递给它(假设它可以用 JSON 表示)。

It works in all current browsers; in case you need a fallback for a reallyold browser, you can use Crockford's JSON-js.

它适用于所有当前浏览器;如果你需要一个非常旧的浏览器的后备,你可以使用Crockford 的 JSON-js

However, keep in mind that, regarding objects, only public properties are serialized. There's no a generic way to serialize function variables etc. on the fly.

但是,请记住,对于对象,只有公共属性会被序列化。没有一种通用的方法来即时序列化函数变量等。

This is why some special object types provide a toJSONor similar method. In order to use such a function for arbitrary objects, you must pass a function as second parameter to JSON.stringifywhich checks for the existence of a toJSONfunction.

这就是为什么一些特殊的对象类型提供了一个toJSON或类似的方法。为了对任意对象使用这样的函数,您必须将函数作为第二个参数传递给JSON.stringify它来检查toJSON函数是否存在。

For example, the following should work (not tested, just from the top of my mind):

例如,以下应该有效(未经测试,只是我的想法):

var jsonString = JSON.stringify(someLargeObject, function(key, value){
    return (value && typeof value.toJSON === 'function') 
        ? value.toJSON()
        : JSON.stringify(value);
});

If your someLargeObjectcontains a sub-object with a toJSONmethod, this code would use the object's implementation, otherwise use JSON.stringify.

如果您someLargeObject包含一个带有toJSON方法的子对象,则此代码将使用该对象的实现,否则使用JSON.stringify.