Advertisement
LarsFosdal

Delphi JSON Reformatter (text or html output)

Sep 27th, 2018
752
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 1.65 KB | None | 0 0
  1. function PrettyFormat(const s: String; const AsHTML:Boolean): String;
  2. // Written by Lars Fosdal, September 2018
  3. var
  4.   sEOL: string;
  5.   sINDENT: string;
  6.   LIndent: string;
  7.   nIndent: Integer;
  8.      procedure Dent;
  9.      var ix: Integer;
  10.      begin
  11.        LIndent := '';
  12.        for ix := 1 to nIndent
  13.         do LIndent := LIndent + sINDENT;
  14.      end;
  15.      procedure Indent;
  16.      begin
  17.        Inc(nIndent);
  18.        Dent;
  19.      end;
  20.      procedure Outdent;
  21.      begin
  22.        Dec(nIndent);
  23.        Dent;
  24.      end;
  25. var
  26.   c: char;
  27.   isInString: boolean;
  28.   isEscape: boolean;
  29.   isUnhandled: boolean;
  30. begin
  31.   Result := '';
  32.   nIndent := 0;
  33.   if AsHTML
  34.   then begin
  35.     sEOL := '<br>';
  36.     sINDENT := '&nbsp;&nbsp;';
  37.   end
  38.   else begin
  39.     sEOL := #13#10;
  40.     sINDENT := '  ';
  41.   end;
  42.   isInString := false;
  43.   isEscape := false;
  44.   LIndent := '';
  45.   for c in s do
  46.   begin
  47.     if not isInString
  48.     then begin
  49.       isUnhandled := True;
  50.       if ((c = '{') or (c = '['))
  51.       then begin
  52.         Indent;
  53.         Result := Result + c + sEOL + LIndent;
  54.         isUnhandled := False;
  55.       end
  56.       else if (c = ',')
  57.       then begin
  58.         Result := Result + c + sEOL  + LIndent;
  59.         isUnhandled := False;
  60.       end
  61.       else if ((c = '}') or (c = ']'))
  62.       then begin
  63.         Outdent;
  64.         Result := Result + sEOL + LIndent + c;
  65.         isUnhandled := False;
  66.       end;
  67.  
  68.       if isUnhandled and not c.IsWhiteSpace
  69.        then Result := Result + c;
  70.     end
  71.      else Result := Result + c;
  72.  
  73.     if not isEscape and (c = '"')
  74.      then isInString := not isInString;
  75.     isEscape := (c = '\') and not isEscape;
  76.   end;
  77. end;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement