In case if somebody will need simple function to decode JSON escaped string:
function JSONUnescape(const Source: string; CRLF: string = #13#10): string;
const
ESCAPE_CHAR = '\';
QUOTE_CHAR = '"';
EXCEPTION_FMT = 'Invalid escape at position %d';
var
EscapeCharPos, TempPos: Integer;
Temp: string;
IsQuotedString: Boolean;
begin
result := '';
IsQuotedString := (Source[1] = QUOTE_CHAR) and
(Source[Length(Source)] = QUOTE_CHAR);
EscapeCharPos := Pos(ESCAPE_CHAR, Source);
TempPos := 1;
while EscapeCharPos > 0 do
begin
result := result + Copy(Source, TempPos, EscapeCharPos - TempPos);
TempPos := EscapeCharPos;
if EscapeCharPos < Length(Source) - Integer(IsQuotedString) then
case Source[EscapeCharPos + 1] of
't':
Temp := #9;
'n':
Temp := CRLF;
'\':
Temp := '\';
'"':
Temp := '"';
'u':
begin
if EscapeCharPos + 4 < Length(Source) - Integer(IsQuotedString) then
Temp := Chr(StrToInt('$' + Copy(Source, EscapeCharPos + 2, 4)))
else
raise Exception.Create(Format(EXCEPTION_FMT, [EscapeCharPos]));
Inc(TempPos, 4);
end;
else
raise Exception.Create(Format(EXCEPTION_FMT, [EscapeCharPos]));
end
else
raise Exception.Create(Format(EXCEPTION_FMT, [EscapeCharPos]));
Inc(TempPos, 2);
result := result + Temp;
EscapeCharPos := Pos(ESCAPE_CHAR, Source, TempPos);
end;
result := result + Copy(Source, TempPos, Length(Source) - TempPos + 1);
end;
Usage:
JSONUnescape('\u2764Love Delphi\u2764');
// Returns '❤Love Delphi❤'
JSONUnescape('"\u2764Love\tDelphi\u2764"');
// Returns '"❤Love Delphi❤"';
JSONUnescape('\\\Invalid escaped text');
// Raises and exception 'Invalid escape at position 3'