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
|
{
This file is part of the Free Component Library
JSON source parser
Copyright (c) 2007 by Michael Van Canneyt michael@freepascal.org
See the file COPYING.FPC, included in this distribution,
for details about the copyright.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
**********************************************************************}
{$mode objfpc}
{$h+}
unit jsonparser;
interface
uses
Classes, SysUtils, fpJSON, jsonscanner;
Type
{ TJSONParser }
TJSONParser = Class(TObject)
Private
FScanner : TJSONScanner;
function ParseNumber: TJSONNumber;
Protected
procedure DoError(Msg: String);
function DoParse(AtCurrent,AllowEOF: Boolean): TJSONData;
function GetNextToken: TJSONToken;
function CurrentTokenString: TJSONStringType;
function CurrentToken: TJSONToken;
function ParseArray: TJSONArray;
function ParseObject: TJSONObject;
Public
function Parse: TJSONData;
Constructor Create(Source : TStream); overload;
Constructor Create(Source : TJSONStringType); overload;
destructor Destroy();override;
end;
EJSONScanner = Class(Exception);
implementation
Resourcestring
SErrUnexpectedEOF = 'Unexpected EOF encountered.';
SErrUnexpectedToken = 'Unexpected token (%s) encountered.';
SErrExpectedColon = 'Expected colon (:), got token "%s".';
SErrUnexpectedComma = 'Invalid comma encountered.';
SErrEmptyElement = 'Empty element encountered.';
SErrExpectedElementName = 'Expected element name, got token "%s"';
SExpectedCommaorBraceClose = 'Expected , or ], got token "%s".';
SErrInvalidNumber = 'Number is not an integer or real number: %s';
{ TJSONParser }
Function TJSONParser.Parse : TJSONData;
begin
Result:=DoParse(False,True);
end;
{
Consume next token and convert to JSON data structure.
If AtCurrent is true, the current token is used. If false,
a token is gotten from the scanner.
If AllowEOF is false, encountering a tkEOF will result in an exception.
}
Function TJSONParser.CurrentToken : TJSONToken;
begin
Result:=FScanner.CurToken;
end;
Function TJSONParser.CurrentTokenString : TJSONStringType;
begin
If CurrentToken in [tkString,tkNumber] then
Result:=FScanner.CurTokenString
else
Result:=TokenInfos[CurrentToken];
end;
Function TJSONParser.DoParse(AtCurrent,AllowEOF : Boolean) : TJSONData;
var
T : TJSONToken;
begin
Result:=nil;
try
If not AtCurrent then
T:=GetNextToken
else
T:=FScanner.CurToken;
Case T of
tkEof : If Not AllowEof then
DoError(SErrUnexpectedEOF);
tkNull : Result:=TJSONNull.Create;
tkTrue,
tkFalse : Result:=TJSONBoolean.Create(t=tkTrue);
tkString : Result:=TJSONString.Create(CurrentTokenString);
tkCurlyBraceOpen : Result:=ParseObject;
tkCurlyBraceClose : DoError(SErrUnexpectedToken);
tkSQuaredBraceOpen : Result:=ParseArray;
tkSQuaredBraceClose : DoError(SErrUnexpectedToken);
tkNumber : Result:=ParseNumber;
tkComma : DoError(SErrUnexpectedToken);
end;
except
if assigned(Result) then
FreeAndNil(Result);
Raise;
end;
end;
// Creates the correct JSON number type, based on the current token.
Function TJSONParser.ParseNumber : TJSONNumber;
Var
I : Int64;
F : TJSONFloat;
S : TJSONStringType;
Error : word;
begin
S:=CurrentTokenString;
I:=0;
If TryStrToInt64(S,I) and (I >= Low(LongInt)) and (I <= High(LongInt)) then
Result:=TJSONIntegerNumber.Create(I)
else
begin
I:=0;
Val(S,F,Error);
If (Error<>0) then
DoError(SErrInvalidNumber);
Result:=TJSONFloatNumber.Create(F);
end;
end;
// Current token is {, on exit current token is }
Function TJSONParser.ParseObject : TJSONObject;
Var
T : TJSONtoken;
E : TJSONData;
N : TJSONStringType;
begin
Result:=TJSONObject.Create;
Try
T:=GetNextToken;
While T<>tkCurlyBraceClose do
begin
If T<>tkString then
DoError(SErrExpectedElementName);
N:=CurrentTokenString;
T:=GetNextToken;
If (T<>tkColon) then
DoError(SErrExpectedColon);
E:=DoParse(False,False);
Result.Add(N,E);
T:=GetNextToken;
If Not (T in [tkComma,tkCurlyBraceClose]) then
DoError(SExpectedCommaorBraceClose);
If T=tkComma then
T:=GetNextToken;
end;
Except
FreeAndNil(Result);
Raise;
end;
end;
// Current token is [, on exit current token is ]
Function TJSONParser.ParseArray : TJSONArray;
Var
T : TJSONtoken;
E : TJSONData;
LastComma : Boolean;
begin
Result:=TJSONArray.Create;
LastComma:=False;
Try
Repeat
T:=GetNextToken;
If (T<>tkSquaredBraceClose) then
begin
E:=DoParse(True,False);
If (E<>Nil) then
Result.Add(E)
else if (Result.Count>0) then
DoError(SErrEmptyElement);
T:=GetNextToken;
If Not (T in [tkComma,tkSquaredBraceClose]) then
DoError(SExpectedCommaorBraceClose);
LastComma:=(t=TkComma);
end;
Until (T=tkSquaredBraceClose);
If LastComma then // Test for ,] case
DoError(SErrUnExpectedToken);
Except
FreeAndNil(Result);
Raise;
end;
end;
// Get next token, discarding whitespace
Function TJSONParser.GetNextToken : TJSONToken ;
begin
Repeat
Result:=FScanner.FetchToken;
Until (Result<>tkWhiteSpace);
end;
Procedure TJSONParser.DoError(Msg : String);
Var
S : TJSONStringType;
begin
S:=Format(Msg,[CurrentTokenString]);
S:=Format('Error at line %d, Pos %d:',[FScanner.CurRow,FSCanner.CurColumn])+S;
Raise EJSONScanner.Create(S);
end;
constructor TJSONParser.Create(Source: TStream);
begin
Inherited Create;
FScanner:=TJSONScanner.Create(Source);
end;
constructor TJSONParser.Create(Source: TJSONStringType);
begin
Inherited Create;
FScanner:=TJSONScanner.Create(Source);
end;
destructor TJSONParser.Destroy();
begin
FreeAndNil(FScanner);
inherited Destroy();
end;
end.
|