1

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.

4
  • 2
    Why JSON at all? Just iterate through the object and replace the values directly. There are a bunch of questions that will have a solution on how to do exactly that. Commented Aug 18, 2021 at 9:23
  • 1
    Does this answer your question? Dynamically change nested JSON Commented Aug 18, 2021 at 9:26
  • because password is password not user.password Commented Aug 18, 2021 at 9:26
  • 1
    Note that what you've called inputJsonObject is not JSON, it's just an object. JSON is a textual notation for data exchange. (More here.) If you're dealing with JavaScript source code, and not dealing with a string, you're not dealing with JSON. (Similarly, hideDataMethod isn't a method, it's a string.) Commented Aug 18, 2021 at 9:26

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.