0

Is there a way to divide/simplify a pattern match to avoid getting this error ? Sometimes the Json String that I'm trying to match is way too long and it causes errors on a batch a class.

I am currently using 2 regex to process the data on the string. Code:

    String fieldsGroup = String.join(fieldsToConvertToList, '"|"');
    fieldsGroup = '("' + fieldsGroup + '")'; 
    String fieldsRegex = fieldsGroup + '(:")(.[^",]+)*(",)'; 
    System.debug(fieldsRegex);
    System.debug(jsonData.length());
    Pattern myPattern = Pattern.compile(fieldsRegex); 
    Matcher myMatcher = myPattern.matcher(jsonData);
    System.debug('matcher: ' + myMatcher);
    while(myMatcher.find()){
        if(myMatcher.groupCount() == 4){
            String stringToReplace = myMatcher.group(0);
            String replacementString = myMatcher.group(1) + ':["' + myMatcher.group(3) + '"],';
            System.debug(stringToReplace);
            System.debug(replacementString);
            jsonData = jsonData.replaceFirst(stringToReplace, replacementString);
        }
    }

    String regex = '(\\s|:|_|-||)(?=[^":]*":)';
    jsonData = jsonData.replaceAll(regex, '');
3

1 Answer 1

2

A regular expression isn't appropriate here. Use the JSON language features.

Map<String, Object> jsonData = (Map<String, Object>)jsonString.deserializeUntyped();
for(String fieldToConvertToList: fieldsToConvertToList) {
  Object value = jsonData.get(fieldToConvertToList);
  if(value instanceOf String) {
    jsonData.put(fieldToConvertToList, ((String)value).split(','));
  }
}

You could also use JSONParser, which is slower, but easier to handle recursion, etc.

As a general rule, you shouldn't be manipulating JSON manually. For example, you've forgotten about escaped quotes inside string properties. Someone some day might experience a bug because quotes were not anticipated. Using language features prevents that from happening.

You could also technically just use indexOf to find each field and the values from there, but again, this is more complicated than it has to be.

2
  • I understand. My JSON structure is a bit complex so I'm not sure if this could work(Objects might be inside of an array). Also, this might solve the issue with the first regex, but the second one(Which removes spaces from attributes to parse fields into a wrapper) still will have the same problem.
    – peepoCode
    Feb 6 at 19:38
  • @peepoCode You can use instanceOf to recursively parse any level of complexity. This answer didn't go there because you didn't mention complexity, but I kind of guessed there may have been.
    – sfdcfox
    Feb 6 at 21:00

Not the answer you're looking for? Browse other questions tagged .