隐藏JSON.stringify()输出中的某些值 [英] Hide certain values in output from JSON.stringify()
问题描述
是否可以排除某些字段包含在json字符串中?
Is it possible to exclude certain fields from being included in the json string?
这是一些伪代码
var x = {
x:0,
y:0,
divID:"xyz",
privateProperty1: 'foo',
privateProperty2: 'bar'
}
我想排除privateProperty1和privateproperty2出现在json字符串中
I want to exclude privateProperty1 and privateproperty2 from appearing in the json string
所以我想,我可以使用stringify替换函数
So I thought, I can use the stringify replacer function
function replacer(key,value)
{
if (key=="privateProperty1") then retun "none";
else if (key=="privateProperty2") then retun "none";
else return value;
}
和stringify
and in the stringify
var jsonString = json.stringify(x,replacer);
但是在jsonString中我仍然认为它是
But in the jsonString I still see it as
{...privateProperty1:value..., privateProperty2:value }
我想要没有privateproperties的字符串。
I would like to the string without the privateproperties in them.
推荐答案
Mozilla docs 说返回 undefined
(而不是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 is a duplication method, in case you decide to go that route (as per your comment).
http://jsfiddle.net/userdude/ 644sJ /
function omitKeys(obj, keys)
{
var dup = {};
for (var 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 - I changed the function key in the bottom function to keep it from being confusing.
这篇关于隐藏JSON.stringify()输出中的某些值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!