LarsFosdal icon

Delphi JSON Reformatter (text or html output)

LarsFosdal | PRO | 09/27/18 02:51:31 PM UTC | 0 ⭐ | 11097 👁️ | Never ⏰ | []
Delphi |

1.65 KB

|

None

|

0 👍

/

0 👎

function PrettyFormat(const s: String; const AsHTML:Boolean): String;
// Written by Lars Fosdal, September 2018
var
  sEOL: string;
  sINDENT: string;
  LIndent: string;
  nIndent: Integer;
     procedure Dent;
     var ix: Integer;
     begin
       LIndent := '';
       for ix := 1 to nIndent
        do LIndent := LIndent + sINDENT;
     end;
     procedure Indent;
     begin
       Inc(nIndent);
       Dent;
     end;
     procedure Outdent;
     begin
       Dec(nIndent);
       Dent;
     end;
var
  c: char;
  isInString: boolean;
  isEscape: boolean;
  isUnhandled: boolean;
begin
  Result := '';
  nIndent := 0;
  if AsHTML
  then begin
    sEOL := '<br>';
    sINDENT := '&nbsp;&nbsp;';
  end
  else begin
    sEOL := #13#10;
    sINDENT := '  ';
  end;
  isInString := false;
  isEscape := false;
  LIndent := '';
  for c in s do
  begin
    if not isInString
    then begin
      isUnhandled := True;
      if ((c = '{') or (c = '['))
      then begin
        Indent;
        Result := Result + c + sEOL + LIndent;
        isUnhandled := False;
      end
      else if (c = ',')
      then begin
        Result := Result + c + sEOL  + LIndent;
        isUnhandled := False;
      end
      else if ((c = '}') or (c = ']'))
      then begin
        Outdent;
        Result := Result + sEOL + LIndent + c;
        isUnhandled := False;
      end;
 
      if isUnhandled and not c.IsWhiteSpace
       then Result := Result + c;
    end
     else Result := Result + c;
 
    if not isEscape and (c = '"')
     then isInString := not isInString;
    isEscape := (c = '\') and not isEscape;
  end;
end;

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎