Skip to content
Advertisement

jsonObject as string – searching for regular expression to remove password field

I have a json String which will have somewhere in its content a string like this:

 "password": "password2"

This can be anywhere in the json string, so don’t assume it’s on the first level. it can even be in a jsonArray. So I need to search the entire string and remove this field, or put its value as null.

So I need to be able to search the entire string and replace the password. For example the string could look like this:

I just want it for logging. My issue is, I want to remove the password value as I am sharing it with a 3rd party.

I need in java to use a regular expression that will search this string and replace the password value with an empty string, or I can do md5 of password even. It must not fail if there is no password string existing. How can I do this? So to be clear, given any input as a string I want the result after filter to be:

 "password": ""

Or it can be a md5 of password value instead of null if its easier. Can you help?

So the function I want to create will look like this:

public String removePasswordFromJsonString(String jsonString){


  //.. do the regualar expression work here....

  return jsonString;

}

Advertisement

Answer

Try this:

public String removePasswordFromJsonString(String jsonString){

  // Handle null input
  if (jsonString == null) {
    return null;
  }

  // Replace all password values with empty strings
  return jsonString.replaceAll(
      "(\n?\s*"password"\s?:\s?")[^\n"]*(",?\n?)", "$1$2");

}

This should be able to replace all occurrences of a password’s value with an empty string, regardless of how deeply nested it is.

EDIT: This will handle zero or one spaces on each side of the colon (:). To handle any number of spaces, use an asterisk (*) instead of a question mark (?):

"(\n?\s*"password"\s*:\s*")[^\n"]*(",?\n?)"

6 People found this is helpful
Advertisement