在*对象的toJSON之前调用replacer *? [英] Call the replacer *before* the object's toJSON?

查看:70
本文介绍了在*对象的toJSON之前调用replacer *?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在对象自己的 toJSON 转换它之前让我的替换器叫做,这样我就可以使用原始对象了比它的JSON友好形式,没有覆盖对象或其原​​型上的 toJSON ,预处理对象,或编写我自己的版本 JSON.stringify

Is there a way to get my replacer called before an object's own toJSON transforms it, so that I can work with the original object rather than its JSON-friendly form, without overriding the toJSON on the object or its prototype, pre-processing the object, or writing my own version of JSON.stringify?

例如:假设我要序列化日期实例与正常序列化不同( toISOString )。 (这个问题特定于日期,这只是一个例子。)问题是,我的替换者没有看到日期对象,它会看到一个字符串(请参阅下面的代码段),因为 Date.prototype.toJSON 在 >我的替换者。

For example: Suppose I want to serialize Date instances differently than their normal serialization (which is toISOString). (This question is not specific to Date, this is just an example.) The problem is, my replacer doesn't see the Date object, it sees a string (see snippet below) because Date.prototype.toJSON is called before my replacer.

var obj = {
  d: new Date()
};
snippet.log(getType(obj.d));     // "[object Date]"

var json = JSON.stringify(obj, function(key, value) {
  if (key === "d") {
    snippet.log(getType(value)); // "string" <== Want to see a Date here
  }
  return value;
});

function getType(value) {
  var to = typeof value;
  if (to === "object") {
    to = Object.prototype.toString.call(value);
  }
  return to;
}

<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

有没有办法让第一个被称为替换者?我不想覆盖 Date.prototype.toJSON ,预处理对象,或编写我自己的 JSON.stringify ,但我没有看到另一种方式。

Is there a way to get the replacer called first? I don't want to override Date.prototype.toJSON, pre-process the object, or write my own JSON.stringify, but I'm not seeing another way.

推荐答案

如果我理解你的话,这应该可以解决问题,我我非常肯定这个始终是对象 JSON.stringify 目前正在迭代:

If I understand you correct this should do the trick, I'm pretty sure this is always the object JSON.stringify is currently iterating over:

var json = JSON.stringify(obj, function(key, value) {
  if (key === "d") {
    snippet.log(getType(this[key]));
  }
  return value;
});

这篇关于在*对象的toJSON之前调用replacer *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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