Apex remove sensitive data from json

When you need to remove sensitive data from json before logging the following method will remove a predefined list of keywords

String bodyArgs = '{"name":"test", "ssn":"324234234", "email":"test@mail.com"}';
Object bodyObj = (Object)JSON.deserializeUntyped(bodyArgs);

Map<String, Object> mapObj = new Map<String, Object>();
if (bodyObj instanceof List<Object>){
	List<Object> lstObjs = (List<Object>)JSON.deserializeUntyped(bodyArgs);
    for (Object lstObj : lstObjs){
       Map<String,Object> parseLstObj = (Map<String,Object>)JSON.deserializeUntyped(JSON.serialize(lstObj));
       mapObj.putAll(parseLstObj);
    }
} else {
	mapObj = (Map<String,Object>)JSON.deserializeUntyped(bodyArgs);
}

Map<String, String> newMappedValues = new Map<String, String>
System.debug(removeAttributes(mapObj, newMappedValues));
>>> Output: '{"name":"test"}'

removeAttributes method will iterate all the keys in the payload and remove the sensitive keys from the payload

private Set<String> removeSensitiveKeyValue = new Set<String>{'ssn', 'email', 'dob'};

public Map<String, String> removeAttributes(Map<String,Object> jsonObj, Map<String, String> mappedKeys)  {
	for(String key : jsonObj.keySet()) {
		if (removeSensitiveKeyValue.contains(key)){
			jsonObj.remove(key);
		} else {
	      if(jsonObj.get(key) instanceof Map<String,Object>) {
	          removeAttributes((Map<String,Object>)jsonObj.get(key), mappedKeys);
	      } else if(jsonObj.get(key) instanceof List<Object>) {
	          for(Object listItem : (List<Object>)jsonObj.get(key)) {
	           if(listItem instanceof Map<String,Object>)  {
	        	removeAttributes((Map<String,Object>)listItem, mappedKeys);
	           }
	         }
	      } else {
			mappedKeys.put(key, String.valueOf(jsonObj.get(key)));
		  }
	  	}
	}
	return mappedKeys;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: