Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the JSON.stringify() replacer function not working?

I have the following code:

http://jsfiddle.net/8tAyu/7/

var foo = {
    "foundation": "Mozilla",
    "model": "box",
    "week": 45,
    "transport": {
        "week": 3
    },
    "month": 7
};

console.log(JSON.stringify(foo, 
                           function(k, v) { 
                               if (k === "week") 
                                   return v;
                               else 
                                   return undefined;
                           }));

so supposedly, I thought at least the "week" that isn't nested should come back, and I will see how to make the nested one come back too. But no matter how I change it, the console.log prints out undefined, unless if I change the function simply to return v always, then I get back the whole object. Why is that?

like image 647
nonopolarity Avatar asked May 02 '13 01:05

nonopolarity


1 Answers

Stringify seems to be called, first, with an empty 'k' for the root of the object. We return undefined for that, and all processing stops.

If we change it to:

if (!k || (k == "week") )

then the result is:

{"week":45}

You won't get the nested one, since we return undefined for "transport" and ignore all its contents.

like image 85
Paul Roub Avatar answered Oct 25 '22 03:10

Paul Roub