Comparison

util/json.lua @ 12792:997f3ca90628 0.12

util.json: Accept empty arrays with whitespace (fixes #1782)
author Matthew Wild <mwild1@gmail.com>
date Fri, 04 Nov 2022 12:26:10 +0000
parent 9329:19bc3ec13f07
child 12975:d10957394a3c
comparison
equal deleted inserted replaced
12790:24b55f0e2db9 12792:997f3ca90628
215 if b ~= 0x2c then return nil, "object eof"; end -- "," 215 if b ~= 0x2c then return nil, "object eof"; end -- ","
216 end 216 end
217 end 217 end
218 local function _readarray(json, index) 218 local function _readarray(json, index)
219 local a = {}; 219 local a = {};
220 local oindex = index;
221 while true do 220 while true do
222 local val; 221 local val, terminated;
223 val, index = _readvalue(json, index + 1); 222 val, index, terminated = _readvalue(json, index + 1, 0x5d);
224 if val == nil then 223 if val == nil then
225 if json:byte(oindex + 1) == 0x5d then return setmetatable(a, array_mt), oindex + 2; end -- "]" 224 if terminated then -- "]" found instead of value
225 if #a ~= 0 then
226 -- A non-empty array here means we processed a comma,
227 -- but it wasn't followed by a value. JSON doesn't allow
228 -- trailing commas.
229 return nil, "value expected";
230 end
231 val, index = setmetatable(a, array_mt), index+1;
232 end
226 return val, index; 233 return val, index;
227 end 234 end
228 t_insert(a, val); 235 t_insert(a, val);
229 index = _skip_whitespace(json, index); 236 index = _skip_whitespace(json, index);
230 local b = json:byte(index); 237 local b = json:byte(index);
292 if a == 0x61 and b == 0x6c and c == 0x73 and d == 0x65 then 299 if a == 0x61 and b == 0x6c and c == 0x73 and d == 0x65 then
293 return false, index + 5; 300 return false, index + 5;
294 end 301 end
295 return nil, "false parse failed"; 302 return nil, "false parse failed";
296 end 303 end
297 function _readvalue(json, index) 304 function _readvalue(json, index, terminator)
298 index = _skip_whitespace(json, index); 305 index = _skip_whitespace(json, index);
299 local b = json:byte(index); 306 local b = json:byte(index);
300 -- TODO try table lookup instead of if-else? 307 -- TODO try table lookup instead of if-else?
301 if b == 0x7B then -- "{" 308 if b == 0x7B then -- "{"
302 return _readobject(json, index); 309 return _readobject(json, index);
310 return _readnull(json, index); 317 return _readnull(json, index);
311 elseif b == 0x74 then -- "t" 318 elseif b == 0x74 then -- "t"
312 return _readtrue(json, index); 319 return _readtrue(json, index);
313 elseif b == 0x66 then -- "f" 320 elseif b == 0x66 then -- "f"
314 return _readfalse(json, index); 321 return _readfalse(json, index);
322 elseif b == terminator then
323 return nil, index, true;
315 else 324 else
316 return nil, "value expected"; 325 return nil, "value expected";
317 end 326 end
318 end 327 end
319 local first_escape = { 328 local first_escape = {