forked from fangq/iso2mesh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loadubjson.m
358 lines (334 loc) · 11.7 KB
/
loadubjson.m
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
function data = loadubjson(fname,varargin)
%
% data=loadubjson(fname,opt)
% or
% data=loadubjson(fname,'param1',value1,'param2',value2,...)
%
% parse a JSON (JavaScript Object Notation) file or string
%
% authors:Qianqian Fang (q.fang <at> neu.edu)
% initially created on 2013/08/01
%
% input:
% fname: input file name, if fname contains "{}" or "[]", fname
% will be interpreted as a UBJSON string
% opt: a struct to store parsing options, opt can be replaced by
% a list of ('param',value) pairs - the param string is equivallent
% to a field in opt. opt can have the following
% fields (first in [.|.] is the default)
%
% SimplifyCell [0|1]: if set to 1, loadubjson will call cell2mat
% for each element of the JSON data, and group
% arrays based on the cell2mat rules.
% IntEndian [B|L]: specify the endianness of the integer fields
% in the UBJSON input data. B - Big-Endian format for
% integers (as required in the UBJSON specification);
% L - input integer fields are in Little-Endian order.
% NameIsString [0|1]: for UBJSON Specification Draft 8 or
% earlier versions (JSONLab 1.0 final or earlier),
% the "name" tag is treated as a string. To load
% these UBJSON data, you need to manually set this
% flag to 1.
% FormatVersion [2|float]: set the JSONLab format version; since
% v2.0, JSONLab uses JData specification Draft 1
% for output format, it is incompatible with all
% previous releases; if old output is desired,
% please set FormatVersion to 1.9 or earlier.
%
% output:
% dat: a cell array, where {...} blocks are converted into cell arrays,
% and [...] are converted to arrays
%
% examples:
% obj=struct('string','value','array',[1 2 3]);
% ubjdata=saveubjson('obj',obj);
% dat=loadubjson(ubjdata)
% dat=loadubjson(['examples' filesep 'example1.ubj'])
% dat=loadubjson(['examples' filesep 'example1.ubj'],'SimplifyCell',1)
%
% license:
% BSD or GPL version 3, see LICENSE_{BSD,GPLv3}.txt files for details
%
% -- this function is part of JSONLab toolbox (http://iso2mesh.sf.net/cgi-bin/index.cgi?jsonlab)
%
if(regexp(fname,'[\{\}\]\[]','once'))
string=fname;
elseif(exist(fname,'file'))
fid = fopen(fname,'rb');
string = fread(fid,inf,'uint8=>char')';
fclose(fid);
else
error('input file does not exist');
end
pos = 1; inputlen = length(string); inputstr = string;
arraytoken=find(inputstr=='[' | inputstr==']' | inputstr=='"');
jstr=regexprep(inputstr,'\\\\',' ');
escquote=regexp(jstr,'\\"');
arraytoken=sort([arraytoken escquote]);
opt=varargin2struct(varargin{:});
opt.arraytoken_=arraytoken;
[os,maxelem,systemendian]=computer;
opt.flipendian_=(systemendian ~= upper(jsonopt('IntEndian','B',opt)));
jsoncount=1;
while pos <= inputlen
[cc, pos]=next_char(inputstr, pos);
switch(cc)
case '{'
[data{jsoncount}, pos] = parse_object(inputstr, pos, opt);
case '['
[data{jsoncount}, pos] = parse_array(inputstr, pos, opt);
otherwise
error_pos('Outer level structure must be an object or an array', inputstr, pos);
end
jsoncount=jsoncount+1;
end % while
jsoncount=length(data);
if(jsoncount==1 && iscell(data))
data=data{1};
end
if(jsonopt('JDataDecode',1,varargin{:})==1)
data=jdatadecode(data,'Base64',0,'Recursive',1,varargin{:});
end
end
%%-------------------------------------------------------------------------
%% helper functions
%%-------------------------------------------------------------------------
function [data, adv]=parse_block(inputstr, pos, type,count,varargin)
[cid,len]=elem_info(inputstr, pos, type);
datastr=inputstr(pos:pos+len*count-1);
newdata=uint8(datastr);
id=strfind('iUIlLdD',type);
if(jsonopt('flipendian_',1,varargin{:}))
newdata=swapbytes(typecast(newdata,cid));
end
data=typecast(newdata,cid);
adv=double(len*count);
end
%%-------------------------------------------------------------------------
function [object, pos] = parse_array(inputstr, pos, varargin) % JSON array is written in row-major order
pos=parse_char(inputstr, pos, '[');
object = cell(0, 1);
dim=[];
type='';
count=-1;
[cc,pos]=next_char(inputstr,pos);
if(cc == '$')
type=inputstr(pos+1);
pos=pos+2;
end
[cc,pos]=next_char(inputstr,pos);
if(cc == '#')
pos=pos+1;
[cc,pos]=next_char(inputstr,pos);
if(cc=='[')
[dim, pos]=parse_array(inputstr, pos, varargin{:});
count=prod(double(dim));
else
[val,pos]=parse_number(inputstr,pos, varargin{:});
count=double(val);
end
end
if(~isempty(type))
if(count>=0)
[object, adv]=parse_block(inputstr, pos, type,count,varargin{:});
if(~isempty(dim))
object=reshape(object,dim);
end
pos=pos+adv;
return;
else
endpos=match_bracket(inputstr,pos);
[cid,len]=elem_info(inputstr, pos, type);
count=(endpos-pos)/len;
[object, adv]=parse_block(inputstr, pos, type,count,varargin{:});
pos=pos+adv;
pos=parse_char(inputstr, pos, ']');
return;
end
end
[cc,pos]=next_char(inputstr,pos);
if cc ~= ']'
while 1
[val, pos] = parse_value(inputstr, pos, varargin{:});
object{end+1} = val;
[cc,pos]=next_char(inputstr,pos);
if cc == ']'
break;
end
end
end
if(jsonopt('SimplifyCell',0,varargin{:})==1)
try
oldobj=object;
object=cell2mat(object')';
if(iscell(oldobj) && isstruct(object) && numel(object)>1 && jsonopt('SimplifyCellArray',1,varargin{:})==0)
object=oldobj;
elseif(size(object,1)>1 && ismatrix(object))
object=object';
end
catch
end
end
if(count==-1)
pos=parse_char(inputstr, pos, ']');
end
end
%%-------------------------------------------------------------------------
function pos=parse_char(inputstr, pos, c)
if pos > length(inputstr) || inputstr(pos) ~= c
error_pos(sprintf('Expected %c at position %%d', c),inputstr, pos);
else
pos = pos + 1;
end
end
%%-------------------------------------------------------------------------
function [c, pos] = next_char(inputstr, pos)
if pos > length(inputstr)
c = [];
else
c = inputstr(pos);
end
end
%%-------------------------------------------------------------------------
function [str, pos] = parse_name(inputstr, pos, varargin)
[val, pos]=parse_number(inputstr,pos,varargin{:});
bytelen=double(val);
if(length(inputstr)>=pos+bytelen-1)
str=inputstr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of name', inputstr, pos);
end
end
%%-------------------------------------------------------------------------
function [str, pos] = parseStr(inputstr, pos, varargin)
type=inputstr(pos);
if type ~= 'S' && type ~= 'C' && type ~= 'H'
error_pos('String starting with S expected at position %d',inputstr, pos);
else
pos = pos + 1;
end
if(type == 'C')
str=inputstr(pos);
pos=pos+1;
return;
end
[val, pos]=parse_number(inputstr,pos,varargin{:});
bytelen=double(val);
if(length(inputstr)>=pos+bytelen-1)
str=inputstr(pos:pos+bytelen-1);
pos=pos+bytelen;
else
error_pos('End of file while expecting end of inputstr',inputstr, pos);
end
end
%%-------------------------------------------------------------------------
function [num, pos] = parse_number(inputstr, pos, varargin)
id=strfind('iUIlLdD',inputstr(pos));
if(isempty(id))
error_pos('expecting a number at position %d',inputstr, pos);
end
type={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
datastr=inputstr(pos+1:pos+bytelen(id));
newdata=uint8(datastr);
if(jsonopt('flipendian_',1,varargin{:}))
newdata=swapbytes(typecast(newdata,type{id}));
end
num=typecast(newdata,type{id});
pos = pos + bytelen(id)+1;
end
%%-------------------------------------------------------------------------
function [val, pos] = parse_value(inputstr, pos, varargin)
switch(inputstr(pos))
case {'S','C','H'}
[val, pos] = parseStr(inputstr, pos, varargin{:});
return;
case '['
[val, pos] = parse_array(inputstr, pos, varargin{:});
return;
case '{'
[val, pos] = parse_object(inputstr, pos, varargin{:});
return;
case {'i','U','I','l','L','d','D'}
[val, pos] = parse_number(inputstr, pos, varargin{:});
return;
case 'T'
val = true;
pos = pos + 1;
return;
case 'F'
val = false;
pos = pos + 1;
return;
case {'Z','N'}
val = [];
pos = pos + 1;
return;
end
error_pos('Value expected at position %d', inputstr, pos);
end
%%-------------------------------------------------------------------------
function pos=error_pos(msg, inputstr, pos)
poShow = max(min([pos-15 pos-1 pos pos+20],length(inputstr)),1);
if poShow(3) == poShow(2)
poShow(3:4) = poShow(2)+[0 -1]; % display nothing after
end
msg = [sprintf(msg, pos) ': ' ...
inputstr(poShow(1):poShow(2)) '<error>' inputstr(poShow(3):poShow(4)) ];
error( ['JSONparser:invalidFormat: ' msg] );
end
%%-------------------------------------------------------------------------
function [object, pos] = parse_object(inputstr, pos, varargin)
pos=parse_char(inputstr,pos,'{');
object = [];
type='';
count=-1;
[cc, pos]=next_char(inputstr,pos);
if(cc == '$')
type=inputstr(pos+1); % TODO
pos=pos+2;
end
[cc, pos]=next_char(inputstr,pos);
if(cc == '#')
pos=pos+1;
[val,pos]=parse_number(inputstr, pos, varargin{:});
count=double(val);
end
[cc, pos]=next_char(inputstr,pos);
if cc ~= '}'
num=0;
while 1
if(jsonopt('NameIsString',0,varargin{:}))
[str, pos] = parseStr(inputstr, pos, varargin{:});
else
[str, pos] = parse_name(inputstr, pos, varargin{:});
end
if isempty(str)
error_pos('Name of value at position %d cannot be empty', inputstr, pos);
end
[val, pos] = parse_value(inputstr, pos, varargin{:});
num=num+1;
object.(encodevarname(str,varargin{:}))=val;
[cc, pos]=next_char(inputstr,pos);
if cc == '}' || (count>=0 && num>=count)
break;
end
end
end
if(count==-1)
pos=parse_char(inputstr, pos, '}');
end
end
%%-------------------------------------------------------------------------
function [cid,len]=elem_info(inputstr, pos, type)
id=strfind('iUIlLdD',type);
dataclass={'int8','uint8','int16','int32','int64','single','double'};
bytelen=[1,1,2,4,8,4,8];
if(id>0)
cid=dataclass{id};
len=bytelen(id);
else
error_pos('unsupported type at position %d',inputstr, pos);
end
end