Saidh
Saidh

Reputation: 1141

JSON Object not fully converts to String?

I am facing an issue that JSON.stringify not stringifies all the keys in a JSON Object.

ie. window.performance.getEntries()[0] contains around 17 keys. But on converting to a string, the result contains only 4 keys.

How can I convert all the keys in window.performance.getEntries()[0]?

I want the complete string output of window.performance.getEntries() which is an array and I used JSON.stringify(window.performance.getEntries()).

Thanks in advance..

Upvotes: 0

Views: 391

Answers (3)

Saidh
Saidh

Reputation: 1141

The simplified solution for this problem which I found is

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

JSON.stringify(jsonArray);

Upvotes: 0

epascarello
epascarello

Reputation: 207511

As other stated it is because there is a toJSON method defined. Basically you need to loop over every index of the array and than every property in the object.

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]));

Upvotes: 0

David P.
David P.

Reputation: 370

window.performance seems to have is own toJSON-function and so can determine what will be stringified. Here is a answer and a work around to your question from a similiar question: https://stackoverflow.com/a/20511811/3400898

"If the stringify method sees an object that contains a toJSON method, it calls that method, and stringifies the value returned. This allows an object to determine its own JSON representation."

Upvotes: 1

Related Questions