Einzelnen Beitrag anzeigen

Benutzerbild von t2000
t2000

Registriert seit: 15. Dez 2005
Ort: NRW
212 Beiträge
 
Delphi 11 Alexandria
 
#1

Replace JSON Escape Steuerzeichen

  Alt 19. Mär 2020, 09:48
Ist das hier die richtige Stelle im Forum?
Soll einfach nur ein Tipp sein.

Ich bekomme über eine REST-Schnittstelle JSON Daten mit Escape-Steuerzeichen. Diese muss ich rausfiltern, bzw. ersetzen.
Da ich nichts gefunden habe, hier meine Routine.

Falls jemand auch sowas sucht

Delphi-Quellcode:
function ReplaceJSONEscape( JSONString: String): String;
// Backslash's ohne richtigen Code bleiben im Text erhalten
var
  p1: Integer;
  l: Integer;
  i: Integer;
  c: Char; // = WideChar
begin
  result := JSONString;
  p1 := pos('\', JSONString);
  l := length(JSONString);
  if (p1 = 0) or (p1 = l) then
    exit;
  c := JSONString[p1+1];
  case c of
    '"' : result := copy( JSONString, 1, p1-1) + '"' + ReplaceJSONEscape( copy( JSONString, p1+2, l-p1-2));
    '\' : result := copy( JSONString, 1, p1-1) + '\' + ReplaceJSONEscape( copy( JSONString, p1+2, l-p1-2));
    '/' : result := copy( JSONString, 1, p1-1) + '/' + ReplaceJSONEscape( copy( JSONString, p1+2, l-p1-2));
    'b' : result := copy( JSONString, 1, p1-1) + #8 + ReplaceJSONEscape( copy( JSONString, p1+2, l-p1-2));
    'f' : result := copy( JSONString, 1, p1-1) + #12 + ReplaceJSONEscape( copy( JSONString, p1+2, l-p1-2));
    'n' : result := copy( JSONString, 1, p1-1) + #10 + ReplaceJSONEscape( copy( JSONString, p1+2, l-p1-2));
    'r' : result := copy( JSONString, 1, p1-1) + #13 + ReplaceJSONEscape( copy( JSONString, p1+2, l-p1-2));
    't' : result := copy( JSONString, 1, p1-1) + #9 + ReplaceJSONEscape( copy( JSONString, p1+2, l-p1-2));
    'u' : begin
            if l < (p1+5) then
              exit;
            i := StrToIntDef('$' + copy( JSONString, p1+2, 4), 0);
            if i = 0 then
              exit;
            result := copy( JSONString, 1, p1-1) + char(i) + ReplaceJSONEscape( copy( JSONString, p1+6, l-p1-6));
          end
    else
      result := copy( JSONString, 1, p1) + ReplaceJSONEscape( copy( JSONString, p1+1, l-p1-1));
  end; // case
end;
Thomas
(Wir suchen eine(n) Entwickler(in) mit Ambitionen später ggf. die Softwarefirma zu leiten)
Aktuell nicht mehr. Aber ab vielleicht 2024/2025 wird das wieder sehr interessant!
  Mit Zitat antworten Zitat