Reputation: 696
I use JSON.stringify(value, replacer)
to mask sensitive data in JSON object.
const inputJsonObject =
{
"id": "uniqueId",
"value": "objectData",
"user": {
"password": "qwerty"
}
};
const hideDataMethod = JSON.stringify(inputJsonObject, (key, value) => {
const dataToHide = ['id', 'user.password'];
return dataToHide.indexOf(key) === -1 ? value : 'xxx';
});
console.log(hideDataMethod);
How to get to user.password
value? The above solution works for id
but doesn't for password.
Upvotes: 1
Views: 1531
Reputation: 1074295
It doesn't work for password
because you're looking for a property called "user.password"
, but there is none; the property's name is password
, not user.password
. (It's a property on an object that's referenced by the user
property on another object, but that has nothing to do with the property name.) If you remove the user.
part of that, it will work. Beware that doing it removes all id
and password
properties from all objects in the object graph being stringified:
const inputObject = {
"id": "uniqueId",
"value": "objectData",
"user": {
"password": "qwerty"
}
};
const dataToHide = ["id", "password"];
const json = JSON.stringify(inputObject, (key, value) => {
return dataToHide.indexOf(key) === -1 ? value : "xxx";
});
console.log(json);
(I also changed the name of a couple of variables that had misleading names.)
But I would sanitize it before converting it to JSON rather than during:
const tmp = {
...inputObject,
id: "xxx",
user: {
...inputObject.user,
password: "xxx",
}
};
const json = JSON.stringify(tmp);
Upvotes: 3