-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathJSON.m
More file actions
267 lines (223 loc) · 9 KB
/
JSON.m
File metadata and controls
267 lines (223 loc) · 9 KB
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
classdef JSON < handle
% v = JSON.parse(jsonString) converts a JSON string to a MATLAB value.
%
% This started out as a recursive descent parser, but JSON is so simple
% that most of the parser collapsed out.
%
% In the service of speed, simplicity, and laziness, this code is NOT a
% validator. Its purpose is to convert correct JSON strings to MATLAB
% values. It does not reject all malformed JSON.
% Copyright 2013 The MathWorks, Inc.
properties (Access = private)
json % the string
index % position in the string
end
methods (Access = private)
function this = JSON(JSONstring)
this.json = JSONstring;
this.index = 1;
end
function value = getValue(this)
% get the next value in the string
[token,tokenType] = this.getNextToken;
value = token;
if strcmp(tokenType,'Special')
if strcmp(token,'{')
value = this.getObject;
elseif strcmp(token,'[')
value = this.getArray;
end
end
end
function array = getArray(this)
% an array is [ value, ... ]
array = {};
value = this.getValue;
while ~strcmp(value,']')
% got a value
array{end+1} = value; %#ok<AGROW> final size is unknowable
% followed by a comma or a "]"
value = this.getValue;
if strcmp(value,',')
value = this.getValue;
elseif strcmp(value,']')
continue
else
error('JSON parser requires commas between array elements');
end
end
% Arrays of all numbers are turned into numeric arrays
fcn = @(x) isnumeric(x) && ~isscalar(x);
if all(cellfun(fcn,array))
array = [array{:}];
end
end
function obj = getObject(this)
% an object is { string : value, ... }
obj = struct;
value = this.getValue;
while ~strcmp(value,'}')
fieldname = value;
% make sure its a valid structure field name
fieldname = strrep(fieldname,':','_');
fieldname = strrep(fieldname,'-','_');
% fix for field names that start with numbers
% Thanks to Guy Ziv!
fieldname = regexprep(fieldname,'(^\d)','s$1');
% check for colon
value = this.getValue;
if ~strcmp(value,':')
error('JSON parser requires colons between object names and values');
end
% get the value
value = this.getValue;
obj.(fieldname) = value;
value = this.getValue;
if strcmp(value,',')
value = this.getValue;
elseif strcmp(value,'}')
continue
else
error('JSON parser requires commas between object elements');
end
end
end
function [token,tokenType] = getNextToken(this)
% get whatever is next in the string
% skip whitespace
ch = this.json(this.index);
while isWhitespace(ch)
this.index = this.index + 1;
ch = this.json(this.index);
end
% is it a special character?
if isSpecial(ch)
token = ch;
tokenType = 'Special';
this.index = this.index + 1;
return
end
% is it one of the three keywords?
switch(ch)
case 't'
match(this,'true');
token = true;
tokenType = 'Logical';
return;
case 'f'
match(this,'false');
tokenType = 'Logical';
token = false;
return;
case 'n'
match(this,'null');
tokenType = 'Null';
token = [];
return;
end
% is it a string?
if(ch == '"')
token = getString(this);
tokenType = 'String';
return;
end
% well, then it better be a number
token = getNumber(this);
tokenType = 'Number';
function match(this,str)
% find and consume exactly str at the current location of error
n = length(str);
range = this.index:(this.index + n - 1);
found = this.json(range);
if strcmp(str,found)
this.index = this.index + n;
else
error('The JSON parser expected "%s" but found %s',str,found)
end
end
function tf = isWhitespace(aChar)
% space, carrage return, linefeed, horizontal tab
tf = aChar == 32 || aChar == 10 || aChar == 13 || aChar == 9;
end
function tf = isSpecial(aChar)
% the special characters in the JSON "language"
tf = aChar == '{' || aChar == '}' || aChar == '['|| aChar == ']'|| aChar == ':' || aChar == ',';
end
function string = getString(this)
first = this.index + 1;
last = first;
str = this.json;
ch = str(last);
while ch ~= '"'
if(ch == '\\') %#ok<STCMP> We KNOW both are single chars
last = last + 2;
else
last = last + 1;
end
ch = str(last);
end
% get the string without it's quotes
string = str(first:(last-1));
this.index = last + 1; % skip the trailing "
end
function number = getNumber(this)
first = this.index;
last = first;
ch = charAt(this,first);
if(ch == '-')
last = last + 1;
ch = charAt(this,last);
end
while isDigit(ch)
last = last + 1;
ch = charAt(this,last);
end
if(ch == '.')
last = last + 1;
ch = charAt(this,last);
while isDigit(ch)
last = last + 1;
ch = charAt(this,last);
end
end
if ch == 'e' || ch == 'E'
last = last + 1;
ch = charAt(this,last);
if ismember(ch,'+-')
last = last + 1;
ch = charAt(this,last);
end
while isDigit(ch)
last = last + 1;
ch = charAt(this,last);
end
end
% pull out the string
str = this.json(first:(last-1));
number = str2double(str);
% move past it
this.index = last;
% helper functions
function char = charAt(this,position)
if(position > length(this.json))
char = 0;
else
char = this.json(position);
end
end
function tf = isDigit(aChar)
tf = aChar > 47 && aChar < 58;
end
end
end
end
methods(Static)
% This is the one method you should call from outside the file.
% JSON.parse(string)... that should be familiar to Javascrpt
% programmers
function value = parse(JSONstring)
jsonObject = JSON(JSONstring);
value = jsonObject.getValue;
end
end
end