-
Notifications
You must be signed in to change notification settings - Fork 0
/
Parser.JSON.pas
1569 lines (1463 loc) · 35.8 KB
/
Parser.JSON.pas
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{==============================================================================|
| Project : JSON/YAML Parser Tools for Object Pascal |
|==============================================================================|
| Content: JSON parser/serializer tools |
|==============================================================================|
| Copyright (c) 2024, Vahid Nasehi Oskouei |
| All rights reserved. |
| |
| License: MIT License |
| |
| Remastered and rewritten version originally based on a work by: |
| Json Tools Pascal Unit |
| A small json parser with no dependencies |
| http://www.getlazarus.org/json |
| |
| Project download homepage: |
| https://github.com/biot2/Yaml.Json.Parser |
| |
| History: |
| 2024-10-05 |
| - Support both Delphi and Free Pascal |
| - Forced utf-8 (AnsiString) unicode support |
| |
|==============================================================================}
unit Parser.JSON;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
Classes, SysUtils;
{ EJSONException is the exception type used by TJSONNode. It is thrown
during parse if the string is invalid json or if an attempt is made to
access a non collection by name or index. }
type
EJSONException = class(Exception);
{ TJSONNodeKind is 1 of 6 possible values described below }
TJSONNodeKind = (
{ Object such as { }
nkObject,
{ Array such as [ ] }
nkArray,
{ The literal values true or false }
nkBool,
{ The literal value null }
nkNull,
{ A number value such as 123, 1.23e2, or -1.5 }
nkNumber,
{ A string such as "hello\nworld!" }
nkString);
TJSONNode = class;
{ TJSONNodeEnumerator is used to enumerate 'for ... in' statements }
TJSONNodeEnumerator = record
private
FNode: TJSONNode;
FIndex: Integer;
public
procedure Init(Node: TJSONNode);
function GetCurrent: TJSONNode;
function MoveNext: Boolean;
property Current: TJSONNode read GetCurrent;
end;
{ TJSONNode is the class used to parse, build, and navigate a json document.
You should only create and free the root node of your document. The root
node will manage the lifetime of all children through methods such as Add,
Delete, and Clear.
When you create a TJSONNode node it will have no parent and is considered to
be the root node. The root node must be either an array or an object. Attempts
to convert a root to anything other than array or object will raise an
exception.
Note: The parser supports unicode by converting unicode characters escaped as
values such as \u20AC. If your json string has an escaped unicode character it
will be unescaped when converted to a pascal string.
See also:
JsonStringDecode to convert a JSON string to a normal string
JsonStringEncode to convert a normal string to a JSON string }
TJSONNode = class
private
FStack: Integer;
FParent: TJSONNode;
FName: AnsiString;
FKind: TJSONNodeKind;
FValue: AnsiString;
FList: TList;
procedure ParseObject(Node: TJSONNode; var C: PChar);
procedure ParseArray(Node: TJSONNode; var C: PChar);
procedure Error(const Msg: AnsiString = '');
function Format(const Indent: AnsiString): AnsiString;
function FormatCompact: AnsiString;
function Add(Kind: TJSONNodeKind; const Name, Value: AnsiString): TJSONNode; overload;
function GetRoot: TJSONNode;
procedure SetKind(Value: TJSONNodeKind);
function GetName: AnsiString;
procedure SetName(const Value: AnsiString);
function GetValue: AnsiString;
function GetCount: Integer;
function GetAsJson: AnsiString;
function GetAsArray: TJSONNode;
function GetAsObject: TJSONNode;
function GetAsNull: TJSONNode;
function GetAsBoolean: Boolean;
procedure SetAsBoolean(Value: Boolean);
function GetAsString: AnsiString;
procedure SetAsString(const Value: AnsiString);
function GetAsNumber: Double;
procedure SetAsNumber(Value: Double);
public
{ A parent node owns all children. Only destroy a node if it has no parent.
To destroy a child node use Delete or Clear methods instead. }
destructor Destroy; override;
{ GetEnumerator adds 'for ... in' statement support }
function GetEnumerator: TJSONNodeEnumerator;
{ Loading and saving methods }
procedure LoadFromStream(Stream: TStream);
procedure SaveToStream(Stream: TStream);
procedure LoadFromFile(const FileName: AnsiString);
procedure SaveToFile(const FileName: AnsiString);
{ Convert a json string into a value or a collection of nodes. If the
current node is root then the json must be an array or object. }
procedure Parse(const Json: AnsiString);
{ The same as Parse, but returns true if no exception is caught }
function TryParse(const Json: AnsiString): Boolean;
{ Add a child node by node kind. If the current node is an array then the
name parameter will be discarded. If the current node is not an array or
object the Add methods will convert the node to an object and discard
its current value.
Note: If the current node is an object then adding an existing name will
overwrite the matching child node instead of adding. }
function Add(const Name: AnsiString; K: TJSONNodeKind = nkObject): TJSONNode; overload;
function Add(const Name: AnsiString; B: Boolean): TJSONNode; overload;
function Add(const Name: AnsiString; const N: Double): TJSONNode; overload;
function Add(const Name: AnsiString; const S: AnsiString): TJSONNode; overload;
{ Convert to an array and add an item }
function Add: TJSONNode; overload;
{ Delete a child node by index or name }
procedure Delete(Index: Integer); overload;
procedure Delete(const Name: AnsiString); overload;
{ Remove all child nodes }
procedure Clear;
{ Get a child node by index. EJSONException is raised if node is not an
array or object or if the index is out of bounds.
See also: Count }
function Child(Index: Integer): TJSONNode; overload;
{ Get a child node by name. If no node is found nil will be returned. }
function Child(const Name: AnsiString): TJSONNode; overload;
{ Search for a node using a path string and return true if exists }
function Exists(const Path: AnsiString): Boolean;
{ Search for a node using a path string }
function Find(const Path: AnsiString): TJSONNode; overload;
{ Search for a node using a path string and return true if exists }
function Find(const Path: AnsiString; out Node: TJSONNode): Boolean; overload;
{ Force a series of nodes to exist and return the end node }
function Force(const Path: AnsiString): TJSONNode;
{ Format the node and all its children as json }
function ToString: AnsiString; override;
{ Root node is read only. A node the root when it has no parent. }
property Root: TJSONNode read GetRoot;
{ Parent node is read only }
property Parent: TJSONNode read FParent;
{ Kind can also be changed using the As methods.
Note: Changes to Kind cause Value to be reset to a default value. }
property Kind: TJSONNodeKind read FKind write SetKind;
{ Name is unique within the scope }
property Name: AnsiString read GetName write SetName;
{ Value of the node in json e.g. '[]', '"hello\nworld!"', 'true', or '1.23e2' }
property Value: AnsiString read GetValue write Parse;
{ The number of child nodes. If node is not an object or array this
property will return 0. }
property Count: Integer read GetCount;
{ AsJson is the more efficient version of Value. Text returned from AsJson
is the most compact representation of the node in json form.
Note: If you are writing a services to transmit or receive json data then
use AsJson. If you want friendly human readable text use Value. }
property AsJson: AnsiString read GetAsJson write Parse;
{ Convert the node to an array }
property AsArray: TJSONNode read GetAsArray;
{ Convert the node to an object }
property AsObject: TJSONNode read GetAsObject;
{ Convert the node to null }
property AsNull: TJSONNode read GetAsNull;
{ Convert the node to a bool }
property AsBoolean: Boolean read GetAsBoolean write SetAsBoolean;
{ Convert the node to a string }
property AsString: AnsiString read GetAsString write SetAsString;
{ Convert the node to a number }
property AsNumber: Double read GetAsNumber write SetAsNumber;
end;
{ JsonValidate tests if a string contains a valid json format }
function JsonValidate(const Json: AnsiString): Boolean;
{ JsonNumberValidate tests if a string contains a valid json formatted number }
function JsonNumberValidate(const N: AnsiString): Boolean;
{ JsonStringValidate tests if a string contains a valid json formatted string }
function JsonStringValidate(const S: AnsiString): Boolean;
{ JsonStringEncode converts a pascal string to a json string }
function JsonStringEncode(const S: AnsiString): AnsiString;
{ JsonStringEncode converts a json string to a pascal string }
function JsonStringDecode(const S: AnsiString): AnsiString;
{ JsonToXml converts a json string to xml }
function JsonToXml(const S: AnsiString): AnsiString;
implementation
resourcestring
SNodeNotCollection = 'Node is not a container';
SRootNodeKind = 'Root node must be an array or object';
SIndexOutOfBounds = 'Index out of bounds';
SParsingError = 'Error while parsing text';
type
TJSONTokenKind = (tkEnd, tkError, tkObjectOpen, tkObjectClose, tkArrayOpen,
tkArrayClose, tkColon, tkComma, tkNull, tkFalse, tkTrue, tkString, tkNumber);
TJSONToken = record
Head: PChar;
Tail: PChar;
Kind: TJSONTokenKind;
function Value: AnsiString;
end;
const
Hex = ['0'..'9', 'A'..'F', 'a'..'f'];
function TJSONToken.Value: AnsiString;
begin
case Kind of
tkEnd: Result := #0;
tkError: Result := #0;
tkObjectOpen: Result := '{';
tkObjectClose: Result := '}';
tkArrayOpen: Result := '[';
tkArrayClose: Result := ']';
tkColon: Result := ':';
tkComma: Result := ',';
tkNull: Result := 'null';
tkFalse: Result := 'false';
tkTrue: Result := 'true';
else
SetString(Result, Head, Tail - Head);
end;
end;
function NextToken(var C: PChar; out T: TJSONToken): Boolean;
begin
if C^ > #0 then
if C^ <= ' ' then
repeat
Inc(C);
if C^ = #0 then
Break;
until C^ > ' ';
T.Head := C;
T.Tail := C;
T.Kind := tkEnd;
if C^ = #0 then
Exit(False);
if C^ = '{' then
begin
Inc(C);
T.Tail := C;
T.Kind := tkObjectOpen;
Exit(True);
end;
if C^ = '}' then
begin
Inc(C);
T.Tail := C;
T.Kind := tkObjectClose;
Exit(True);
end;
if C^ = '[' then
begin
Inc(C);
T.Tail := C;
T.Kind := tkArrayOpen;
Exit(True);
end;
if C^ = ']' then
begin
Inc(C);
T.Tail := C;
T.Kind := tkArrayClose;
Exit(True);
end;
if C^ = ':' then
begin
Inc(C);
T.Tail := C;
T.Kind := tkColon;
Exit(True);
end;
if C^ = ',' then
begin
Inc(C);
T.Tail := C;
T.Kind := tkComma;
Exit(True);
end;
if (C[0] = 'n') and (C[1] = 'u') and (C[2] = 'l') and (C[3] = 'l') then
begin
Inc(C, 4);
T.Tail := C;
T.Kind := tkNull;
Exit(True);
end;
if (C[0] = 'f') and (C[1] = 'a') and (C[2] = 'l') and (C[3] = 's') and (C[4] = 'e') then
begin
Inc(C, 5);
T.Tail := C;
T.Kind := tkFalse;
Exit(True);
end;
if (C[0] = 't') and (C[1] = 'r') and (C[2] = 'u') and (C[3] = 'e') then
begin
Inc(C, 4);
T.Tail := C;
T.Kind := tkTrue;
Exit(True);
end;
if C^ = '"' then
begin
repeat
Inc(C);
if C^ = '\' then
begin
Inc(C);
if C^ < ' ' then
begin
T.Tail := C;
T.Kind := tkError;
Exit(False);
end;
if C^ = 'u' then
if not ((C[1] in Hex) and (C[2] in Hex) and (C[3] in Hex) and (C[4] in Hex)) then
begin
T.Tail := C;
T.Kind := tkError;
Exit(False);
end;
end
else if C^ = '"' then
begin
Inc(C);
T.Tail := C;
T.Kind := tkString;
Exit(True);
end;
until C^ in [#0, #10, #13];
T.Tail := C;
T.Kind := tkError;
Exit(False);
end;
if C^ in ['-', '0'..'9'] then
begin
if C^ = '-' then
Inc(C);
if C^ in ['0'..'9'] then
begin
while C^ in ['0'..'9'] do
Inc(C);
if C^ = '.' then
begin
Inc(C);
if C^ in ['0'..'9'] then
begin
while C^ in ['0'..'9'] do
Inc(C);
end
else
begin
T.Tail := C;
T.Kind := tkError;
Exit(False);
end;
end;
if C^ in ['E', 'e'] then
begin
Inc(C);
if C^ = '+' then
Inc(C)
else if C^ = '-' then
Inc(C);
if C^ in ['0'..'9'] then
begin
while C^ in ['0'..'9'] do
Inc(C);
end
else
begin
T.Tail := C;
T.Kind := tkError;
Exit(False);
end;
end;
T.Tail := C;
T.Kind := tkNumber;
Exit(True);
end;
end;
T.Kind := tkError;
Result := False;
end;
{ TJSONNodeEnumerator }
procedure TJSONNodeEnumerator.Init(Node: TJSONNode);
begin
FNode := Node;
FIndex := -1;
end;
function TJSONNodeEnumerator.GetCurrent: TJSONNode;
begin
if FNode.FList = nil then
Result := nil
else if FIndex < 0 then
Result := nil
else if FIndex < FNode.FList.Count then
Result := TJSONNode(FNode.FList[FIndex])
else
Result := nil;
end;
function TJSONNodeEnumerator.MoveNext: Boolean;
begin
Inc(FIndex);
if FNode.FList = nil then
Result := False
else
Result := FIndex < FNode.FList.Count;
end;
{ TJSONNode }
destructor TJSONNode.Destroy;
begin
Clear;
inherited Destroy;
end;
function TJSONNode.GetEnumerator: TJSONNodeEnumerator;
begin
Result.Init(Self);
end;
procedure TJSONNode.LoadFromStream(Stream: TStream);
var
S: AnsiString;
i: Int64;
begin
i := Stream.Size - Stream.Position;
S := '';
SetLength(S, i);
Stream.Read(PChar(S)^, i);
Parse(S);
end;
procedure TJSONNode.SaveToStream(Stream: TStream);
var
S: AnsiString;
i: Int64;
begin
S := Value;
i := Length(S);
Stream.Write(PChar(S)^, i);
end;
procedure TJSONNode.LoadFromFile(const FileName: AnsiString);
var
F: TFileStream;
begin
F := TFileStream.Create(FileName, fmOpenRead);
try
LoadFromStream(F);
finally
F.Free;
end;
end;
procedure TJSONNode.SaveToFile(const FileName: AnsiString);
var
F: TFileStream;
begin
F := TFileStream.Create(FileName, fmCreate);
try
SaveToStream(F);
finally
F.Free;
end;
end;
const
MaxStack = 1000;
procedure TJSONNode.ParseObject(Node: TJSONNode; var C: PChar);
var
T: TJSONToken;
N: AnsiString;
begin
Inc(FStack);
if FStack > MaxStack then
Error;
while NextToken(C, T) do
begin
case T.Kind of
tkString: N := JsonStringDecode(T.Value);
tkObjectClose:
begin
Dec(FStack);
Exit;
end
else
Error;
end;
NextToken(C, T);
if T.Kind <> tkColon then
Error;
NextToken(C, T);
case T.Kind of
tkObjectOpen: ParseObject(Node.Add(nkObject, N, ''), C);
tkArrayOpen: ParseArray(Node.Add(nkArray, N, ''), C);
tkNull: Node.Add(nkNull, N, 'null');
tkFalse: Node.Add(nkBool, N, 'false');
tkTrue: Node.Add(nkBool, N, 'true');
tkString: Node.Add(nkString, N, T.Value);
tkNumber: Node.Add(nkNumber, N, T.Value);
else
Error;
end;
NextToken(C, T);
if T.Kind = tkComma then
Continue;
if T.Kind = tkObjectClose then
begin
Dec(FStack);
Exit;
end;
Error;
end;
Error;
end;
procedure TJSONNode.ParseArray(Node: TJSONNode; var C: PChar);
var
T: TJSONToken;
begin
Inc(FStack);
if FStack > MaxStack then
Error;
while NextToken(C, T) do
begin
case T.Kind of
tkObjectOpen: ParseObject(Node.Add(nkObject, '', ''), C);
tkArrayOpen: ParseArray(Node.Add(nkArray, '', ''), C);
tkNull: Node.Add(nkNull, '', 'null');
tkFalse: Node.Add(nkBool, '', 'false');
tkTrue: Node.Add(nkBool, '', 'true');
tkString: Node.Add(nkString, '', T.Value);
tkNumber: Node.Add(nkNumber, '', T.Value);
tkArrayClose:
begin
Dec(FStack);
Exit;
end
else
Error;
end;
NextToken(C, T);
if T.Kind = tkComma then
Continue;
if T.Kind = tkArrayClose then
begin
Dec(FStack);
Exit;
end;
Error;
end;
Error;
end;
procedure TJSONNode.Parse(const Json: AnsiString);
var
C: PChar;
T: TJSONToken;
begin
Clear;
C := PChar(Json);
if FParent = nil then
begin
if NextToken(C, T) and (T.Kind in [tkObjectOpen, tkArrayOpen]) then
begin
try
if T.Kind = tkObjectOpen then
begin
FKind := nkObject;
ParseObject(Self, C);
end
else
begin
FKind := nkArray;
ParseArray(Self, C);
end;
NextToken(C, T);
if T.Kind <> tkEnd then
Error;
except
Clear;
raise;
end;
end
else
Error(SRootNodeKind);
end
else
begin
NextToken(C, T);
case T.Kind of
tkObjectOpen:
begin
FKind := nkObject;
ParseObject(Self, C);
end;
tkArrayOpen:
begin
FKind := nkArray;
ParseArray(Self, C);
end;
tkNull:
begin
FKind := nkNull;
FValue := 'null';
end;
tkFalse:
begin
FKind := nkBool;
FValue := 'false';
end;
tkTrue:
begin
FKind := nkBool;
FValue := 'true';
end;
tkString:
begin
FKind := nkString;
FValue := T.Value;
end;
tkNumber:
begin
FKind := nkNumber;
FValue := T.Value;
end;
else
Error;
end;
NextToken(C, T);
if T.Kind <> tkEnd then
begin
Clear;
Error;
end;
end;
end;
function TJSONNode.TryParse(const Json: AnsiString): Boolean;
begin
try
Parse(Json);
Result := True;
except
Result := False;
end;
end;
procedure TJSONNode.Error(const Msg: AnsiString = '');
begin
FStack := 0;
if Msg = '' then
raise EJSONException.Create(SParsingError)
else
raise EJSONException.Create(Msg);
end;
function TJSONNode.GetRoot: TJSONNode;
begin
Result := Self;
while Result.FParent <> nil do
Result := Result.FParent;
end;
procedure TJSONNode.SetKind(Value: TJSONNodeKind);
begin
if Value = FKind then Exit;
case Value of
nkObject: AsObject;
nkArray: AsArray;
nkBool: AsBoolean;
nkNull: AsNull;
nkNumber: AsNumber;
nkString: AsString;
end;
end;
function TJSONNode.GetName: AnsiString;
begin
if FParent = nil then
Exit('0');
if FParent.FKind = nkArray then
Result := IntToStr(FParent.FList.IndexOf(Self))
else
Result := FName;
end;
procedure TJSONNode.SetName(const Value: AnsiString);
var
N: TJSONNode;
begin
if FParent = nil then
Exit;
if FParent.FKind = nkArray then
Exit;
N := FParent.Child(Value);
if N = Self then
Exit;
FParent.FList.Remove(N);
FName := Value;
end;
function TJSONNode.GetValue: AnsiString;
begin
if FKind in [nkObject, nkArray] then
Result := Format('')
else
Result := FValue;
end;
function TJSONNode.GetAsJson: AnsiString;
begin
if FKind in [nkObject, nkArray] then
Result := FormatCompact
else
Result := FValue;
end;
function TJSONNode.GetAsArray: TJSONNode;
begin
if FKind <> nkArray then
begin
Clear;
FKind := nkArray;
FValue := '';
end;
Result := Self;
end;
function TJSONNode.GetAsObject: TJSONNode;
begin
if FKind <> nkObject then
begin
Clear;
FKind := nkObject;
FValue := '';
end;
Result := Self;
end;
function TJSONNode.GetAsNull: TJSONNode;
begin
if FParent = nil then
Error(SRootNodeKind);
if FKind <> nkNull then
begin
Clear;
FKind := nkNull;
FValue := 'null';
end;
Result := Self;
end;
function TJSONNode.GetAsBoolean: Boolean;
begin
if FParent = nil then
Error(SRootNodeKind);
if FKind <> nkBool then
begin
Clear;
FKind := nkBool;
FValue := 'false';
Exit(False);
end;
Result := FValue = 'true';
end;
procedure TJSONNode.SetAsBoolean(Value: Boolean);
begin
if FParent = nil then
Error(SRootNodeKind);
if FKind <> nkBool then
begin
Clear;
FKind := nkBool;
end;
if Value then
FValue := 'true'
else
FValue := 'false';
end;
function TJSONNode.GetAsString: AnsiString;
begin
if FParent = nil then
Error(SRootNodeKind);
if FKind <> nkString then
begin
Clear;
FKind := nkString;
FValue := '""';
Exit('');
end;
Result := JsonStringDecode(FValue);
end;
procedure TJSONNode.SetAsString(const Value: AnsiString);
begin
if FParent = nil then
Error(SRootNodeKind);
if FKind <> nkString then
begin
Clear;
FKind := nkString;
end;
FValue := JsonStringEncode(Value);
end;
function TJSONNode.GetAsNumber: Double;
begin
if FParent = nil then
Error(SRootNodeKind);
if FKind <> nkNumber then
begin
Clear;
FKind := nkNumber;
FValue := '0';
Exit(0);
end;
Result := StrToFloatDef(FValue, 0);
end;
procedure TJSONNode.SetAsNumber(Value: Double);
begin
if FParent = nil then
Error(SRootNodeKind);
if FKind <> nkNumber then
begin
Clear;
FKind := nkNumber;
end;
FValue := FloatToStr(Value);
end;
function TJSONNode.Add: TJSONNode;
begin
Result := AsArray.Add('');
end;
function TJSONNode.Add(Kind: TJSONNodeKind; const Name, Value: AnsiString): TJSONNode;
var
S: AnsiString;
begin
if not (FKind in [nkArray, nkObject]) then
if Name = '' then
AsArray
else
AsObject;
if FKind in [nkArray, nkObject] then
begin
if FList = nil then
FList := TList.Create;
if FKind = nkArray then
S := IntToStr(FList.Count)
else
S := Name;
Result := Child(S);
if Result = nil then
begin
Result := TJSONNode.Create;
Result.FName := S;
FList.Add(Result);
end;
if Kind = nkNull then
Result.FValue := 'null'
else if Kind in [nkBool, nkString, nkNumber] then
Result.FValue := Value
else
begin
Result.FValue := '';
Result.Clear;
end;
Result.FParent := Self;
Result.FKind := Kind;
end
else
Error(SNodeNotCollection);
end;
function TJSONNode.Add(const Name: AnsiString; K: TJSONNodeKind = nkObject): TJSONNode; overload;
begin
case K of
nkObject, nkArray: Result := Add(K, Name, '');
nkNull: Result := Add(K, Name, 'null');
nkBool: Result := Add(K, Name, 'false');
nkNumber: Result := Add(K, Name, '0');
nkString: Result := Add(K, Name, '""');
end;
end;
function TJSONNode.Add(const Name: AnsiString; B: Boolean): TJSONNode; overload;
const
Bools: array[Boolean] of AnsiString = ('false', 'true');
begin
Result := Add(nkBool, Name, Bools[B]);
end;
function TJSONNode.Add(const Name: AnsiString; const N: Double): TJSONNode; overload;
begin
Result := Add(nkNumber, Name, FloatToStr(N));
end;
function TJSONNode.Add(const Name: AnsiString; const S: AnsiString): TJSONNode; overload;
begin
Result := Add(nkString, Name, JsonStringEncode(S));
end;
procedure TJSONNode.Delete(Index: Integer);
var
N: TJSONNode;
begin
N := Child(Index);
if N <> nil then
begin
N.Free;
FList.Delete(Index);
if FList.Count = 0 then
begin
FList.Free;
FList := nil;
end;
end;
end;
procedure TJSONNode.Delete(const Name: AnsiString);
var
N: TJSONNode;
begin
N := Child(Name);
if N <> nil then
begin
N.Free;
FList.Remove(N);
if FList.Count = 0 then
begin
FList.Free;
FList := nil;
end;
end;
end;
procedure TJSONNode.Clear;
var
i: Integer;
begin
if FList <> nil then
begin
for i := 0 to FList.Count - 1 do
TObject(FList[i]).Free;
FList.Free;
FList := nil;
end;