JSON对象未完全转换为字符串

JSON Object not fully converts to String?

本文关键字:转换 字符串 对象 JSON      更新时间:2023-09-26

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

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

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

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

提前谢谢。。

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

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

正如其他人所说,这是因为定义了一个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]));

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

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