-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJSON_Stringify.pp
100 lines (85 loc) · 2.59 KB
/
JSON_Stringify.pp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
unit JSON_Stringify;
{$mode ObjFPC}{$H+}
interface
uses
JSON, SysUtils, StrUtils;
function StringifyJsonValue(Value: TJsonValue): String;
implementation
const CR_LF: PChar = #13#10;
const SOFT_TAB: PChar = ' ';
function EscapeQuotes(S: String): String;
begin
Result := StringReplace(S, '\', '\\', [ rfReplaceAll ]);
Result := StringReplace(Result, '"', '\"', [ rfReplaceAll ]);
end;
function StringifyValueWithPadding(Value: TJsonValue; Padding: String): String;
var
I: Integer;
begin
case Value.DataType of
jsNull:
Result := 'null';
jsString: begin;
if Assigned(Value.StringValue) then
begin
Result := Value.StringValue;
Result := '"' + EscapeQuotes(Result) + '"';
end;
end;
jsInteger:
Result := Format('%D', [ Value.IntegerValue ]);
jsNumber:
Result := Format('%G', [ Value.NumberValue ]);
jsBoolean:
begin
if Value.BooleanValue then
Result := 'true'
else
Result := 'false';
end;
jsObject:
begin
if Length(Value.ObjectValue^) = 0 then
Result := '{}'
else
begin
Result := '{' + CR_LF;
for I := Low(TJsonEntries(Value.ObjectValue)) to High(TJsonEntries(Value.ObjectValue)) do
begin
Result := Result + Padding + SOFT_TAB
+ '"' + TJsonEntries(Value.ObjectValue)[I].Key + '": '
+ StringifyValueWithPadding(TJsonEntries(Value.ObjectValue)[I].Value, Padding + SOFT_TAB);
if I = High(TJsonEntries(Value.ObjectValue)) then
Result := Result + CR_LF
else
Result := Result + ',' + CR_LF
end;
Result := Result + Padding + '}';
end;
end;
jsArray:
begin
if Length(TJsonValues(Value.Items)) = 0 then
Result := '[]'
else
begin
Result := '[' + CR_LF;
for I := Low(TJsonValues(Value.Items)) to High(TJsonValues(Value.Items)) do
begin
Result := Result + Padding + SOFT_TAB
+ StringifyValueWithPadding(TJsonValues(Value.Items)[I], Padding + SOFT_TAB);
if I = High(TJsonValues(Value.Items)) then
Result := Result + CR_LF
else
Result := Result + ',' + CR_LF;
end;
Result := Result + Padding + ']';
end;
end;
end;
end;
function StringifyJsonValue(Value: TJsonValue): String;
begin
Result := StringifyValueWithPadding(Value, '');
end;
end.