lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Duncan, Patrick,

That's an interesting approach!

On Fri, Oct 28, 2011 at 16:14, Patrick Rapin <toupie300@gmail.com> wrote:
> 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.

Is that hard to add?

> 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)

I believe that you o not need a function here, just pass `escapes`
here. Or even put the table directly, to shorten further.

>                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

Anyone knows a good JSON compatibility test suite for the parser?

Alexander.