【问题标题】:JSON Object not fully converts to String?JSON 对象未完全转换为字符串?
【发布时间】:2016-02-13 20:21:48
【问题描述】:

我面临一个问题,即 JSON.stringify 没有对 JSON 对象中的所有键进行字符串化。

即。 window.performance.getEntries()[0] 包含大约 17 个键。但是在转换为字符串时,结果只包含 4 个键。

如何转换window.performance.getEntries()[0]中的所有键?

我想要window.performance.getEntries() 的完整字符串输出,它是一个数组,我使用了JSON.stringify(window.performance.getEntries())

提前谢谢..

【问题讨论】:

  • window.performance.getEntries()[0] 的示例
  • 抱歉,没有示例或截图,我们无法为您提供帮助...
  • 为我工作JSON.parse(JSON.stringify(window.performance.getEntries())).length == window.performance.getEntries().length == true 你检查过解析停止的条目吗?
  • @AlexK。 — window.performance.getEntries() != window.performance.getEntries()[0] 问题是询问返回的数组中对象的属性,而不是数组本身的条目。
  • 是的,但是 我想要 window.performance.getEntries() 的完整字符串输出

标签: javascript json stringify


【解决方案1】:

window.performance 似乎有自己的toJSON-function,因此可以确定将被字符串化的内容。这是一个类似问题的答案和解决方法:https://stackoverflow.com/a/20511811/3400898

“如果 stringify 方法看到一个包含 toJSON 方法的对象,它会调用该方法,并将返回的值字符串化。这允许对象确定自己的 JSON 表示。”

【讨论】:

    【解决方案2】:

    正如其他所说,这是因为定义了一个 toJSON 方法。基本上,您需要遍历数组的每个索引,而不是对象中的每个属性。

    var adjusted = window.performance.getEntries().map( function (result) {       
        var temp = {}, key;
        for (key in result) if (key!=="toJSON") temp[key]=result[key]; 
        return temp;
    });
    console.log(JSON.stringify(adjusted[0]));
    

    【讨论】:

      【解决方案3】:

      我发现的这个问题的简化解决方案是

      var jsonArray = $.map(performance.getEntries(),function(jsonObj){
          var obj = $.extend({},jsonObj);
          delete obj.toJSON;
          return obj;
      });
      
      JSON.stringify(jsonArray);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-07
        相关资源
        最近更新 更多