javascript - Hide certain values in output from JSON.stringify() -
is possible exclude fields being included in json string?
here pseudo code
var x = { x:0, y:0, divid:"xyz", privateproperty1: 'foo', privateproperty2: 'bar' }
i want exclude privateproperty1 , privateproperty2 appearing in json string
so thought, can use stringify replacer function
function replacer(key,value) { if (key=="privateproperty1") retun "none"; else if (key=="privateproperty2") retun "none"; else return value; }
and in stringify
var jsonstring = json.stringify(x,replacer);
but in jsonstring still see as
{...privateproperty1:value..., privateproperty2:value }
i string without privateproperties in them.
the mozilla docs return undefined
instead of "none"
:
http://jsfiddle.net/userdude/rz5px/
function replacer(key,value) { if (key=="privateproperty1") return undefined; else if (key=="privateproperty2") return undefined; else return value; } var x = { x:0, y:0, divid:"xyz", privateproperty1: 'foo', privateproperty2: 'bar' }; alert(json.stringify(x, replacer));
here duplication method, in case decide go route (as per comment).
http://jsfiddle.net/userdude/644sj/
function omitkeys(obj, keys) { var dup = {}; (key in obj) { if (keys.indexof(key) == -1) { dup[key] = obj[key]; } } return dup; } var x = { x:0, y:0, divid:"xyz", privateproperty1: 'foo', privateproperty2: 'bar' }; alert(json.stringify(omitkeys(x, ['privateproperty1','privateproperty2'])));
edit - changed function key in bottom function keep being confusing.
Comments
Post a Comment