Ray Ray - 7 months ago 27
JSON Question

stringify object array to JSON Selectively

I have an Object array named users.
The object format in this array looks like this:

var userExample = {pub:{name:'John', id:'100'}, priv:{location:'NYC', phone:'000000'}};

As a restful service, clients may request information of all users.
And obviously I just want to send public information to them.
So I want to serialize my data selectively by keys(priv key will be ignored)

Here is my code snippet:

var users = [];
function censor(key, value) {
if (key == priv) {
return undefined;
return value;

app.get('/listUsers', function(req, res){
res.end(JSON.stringify(users, censor));

When I run these code, an error occurred:

ReferenceError: priv is not defined

I'm a Javascript beginner, please help.


Change priv to "priv".

But your approach is dangerous. In similar conditions I usually create a new object to export and I explicitly copy the properties which should be exported, this way there's no risk of leak on future data structure changes. A white list is always more future proof than a black list.