1

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?

2
  • 3
    Why regex? Why not use JSON and the available Object and Array methods? Commented Jul 25, 2020 at 16:20
  • Because I am getting these values as JSON to my Node.js backend. The JSON string will be too nested and too big. I don't want to call JSON.parse. I thought it will be faster if I use regex. Commented Jul 25, 2020 at 16:22

2 Answers 2

4

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": "***"
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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);

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.