JSON.stringify loses/missing fields

1.5k views Asked by At

This is my code:

// get from ajax
$.ajax({
    'async': false,
    'global': false,
    'url': url,
    'dataType': "json",
    'success': function (d) {
        data = d;

        // code here to define & calculate voteCount

        data.votes.totalVotes = voteCount;
        localStorage.setItem(url, data);
    }
    , 'error': function (msg) {
        throw new Error("Error retrieving data from " + url);
    }
});

After this line:

data.votes.totalVotes = voteCount;

...in the console, if I type: data.votes.totalVotes, I get the value I am expecting.

However, if I type: JSON.stringify(data), the totalVotes property is not present.

Any idea why not, or how to fix it?

** note: edited because as far as I can tell this is NOT an async issue, the behaviour is present in the success callback too.

2

There are 2 answers

3
digitalextremist On

This is the correct version of your $.ajax call:

var data
$.ajax({
    'async': false,
    'global': false,
    'url': url,
    'dataType': "json",
    'success': function (d) {
        data = d;
        data.votes.totalVotes = voteCount;
        localStorage.setItem("myData", JSON.stringify(data));
    }, 'error': function (msg) {
        throw new Error("Error retrieving data from " + url);
    }
});
0
Sean On

Ok, sorry, I was being daft. votes is an array, so I was setting totalVotes as a property on the array, which is fine in the object, but gets omitted when serialized.

If someone else is as daft as I am, maybe this will help.