[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Smallest Lua-only single-file JSON parser
- From: Patrick Rapin <toupie300@...>
- Date: Fri, 28 Oct 2011 14:14:34 +0200
As an exercise, I tried to wrote the really minimum JSON parser.
It is below (only 10 lines of code)...
It first converts the JSON snipped into a valid Lua expression using
string patterns, then evaluates it.
Bugs apart, the only missing feature is the \uXXXX string escape.
function decode_json(json)
local str = {}
local escapes = { r='\r', n='\n', b='\b', f='\f', t='\t', Q='"',
['\\'] = '\\', ['/']='/' }
json = json:gsub('([^\\])\\"', '%1\\Q'):gsub('"(.-)"', function(s)
str[#str+1] = s:gsub("\\(.)", function(c) return escapes[c] end)
return "$"..#str
end):gsub("%s", ""):gsub("%[","{"):gsub("%]","}"):gsub("null", "nil")
json = json:gsub("(%$%d+):", "[%1]="):gsub("%$(%d+)", function(s)
return ("%q"):format(str[tonumber(s)])
end)
return assert(loadstring("return "..json))()
end