Javith
Javith

Reputation: 41

Obfuscate values in JSON string using Regex

I want to obfuscate values in JSON string using regex.

JSON String:

{
    "filter" : {
        "_id": {
            "$oid" : "5f197831618f147e681d9410"
        },
        "name": "John Doe",
        "age": 3
    }
}

Expected Obfuscation in JSON String:

{
    "filter" : {
        "_id": {
            "$oid" : "xxx"
        },
        "name": "xxx",
        "age": "xxx"
    }
}

How can I do this with Regex?

Upvotes: 1

Views: 3154

Answers (2)

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

Alternatively you could use the replacer callback built into JSON.stringify

const obj = {
  "filter": {
    "_id": {
      "$oid": "5f197831618f147e681d9410"
    },
    "name": "John Doe",
    "age": 3
  }
};

const obfusked = JSON.stringify(obj, (k, v) => ['string', 'number'].includes(typeof v) ? '***' : v, 2)

console.log(obfusked)

Result:

{
  "filter": {
    "_id": {
      "$oid": "***"
    },
    "name": "***",
    "age": "***"
  }
}

Upvotes: 4

Kunal Mukherjee
Kunal Mukherjee

Reputation: 5853

You just need to recursively walk through each property's value and set it to the desired masking character.

The first check is, if its an object you want to descend recursively and if its a primitive value which is there on the current object and not the parent prototype just set the desired masking character.

const obj = {
  "filter": {
    "_id": {
      "$oid": "5f197831618f147e681d9410"
    },
    "name": "John Doe",
    "age": 3
  }
};

const obfuscateRecursively = function(obj, maskValue) {
  for (const key in obj) {
    if (obj[key] && typeof obj[key] === 'object') {
      obfuscateRecursively(obj[key], maskValue);
    } else if (obj.hasOwnProperty(key)) {
      obj[key] = maskValue;
    }
  }
};

// Make deep copy of object first
const deepCopyObj = JSON.parse(JSON.stringify(obj));

// This method will mutate the values recursively to the leaf level
obfuscateRecursively(deepCopyObj, '***');

console.log(deepCopyObj);

Upvotes: 1

Related Questions