Simple JSON formatter in CRMScript

lock
push_pin
done
Besvaret
0

Hi all,

I got a bit fed up of reading unformatted JSON so I wrote a small JSON formatter in CRMScript. It is perhaps not very fast, or bullet proof. Feel free to suggest improvements, but here it is for anyone who finds it useful :-)

String prettyJSON(String source, Integer tabWidth) {
  String lotsOfSpaces = "";
  for (Integer i = 0; i < 256; i++) lotsOfSpaces.append(" ");
  
  String result;
  
  Integer level = 0;
  String spaces;
  String prefix;
  String suffix;
  Bool escaped = false;
  Bool quoted = false;
  for (Integer i = 0; i < source.getLength(); i++) {
    String c = source.subString(i, 1);
    if (escaped) escaped = false;
    else if (c == "\\") escaped = true;
    else if (c == "\"") quoted = !quoted;
    else if (quoted) {} 
    else if (c == "[" || c == "{") {
      level++;
      spaces = lotsOfSpaces.subString(0, level * tabWidth);
      suffix = "\n" + spaces;
    }
    else if (c == "]" || c == "}") {
      level--;
      spaces = lotsOfSpaces.subString(0, level * tabWidth);
      prefix = "\n" + spaces;
    }
    else if (c == ",") {
      suffix = "\n" + spaces;
    }
    else if (c == ":") { 
      suffix = " ";
    }
    else if (c == "\n" || c == "\r" || c == "\t" || c == " ") {
      c = "";
    }
    result.append(prefix);
    result.append(c);
    result.append(suffix);
    prefix = suffix = "";
  }
  return result;
}

Sverre

24. okt. 2023 | 10.44 AM

Alle Svar (0)

Tilføj svar