JSON decoder snippet

While playing with JSON, I’ve never noticed how it was so close to Lua object notation. Here is a 4 lines JSON naive decoder. Sure that will never replace a real decoder…

function jsondecode(json)
	local json,c = string.gsub(json,'(%[([^%[%]].-)%])','{%2}')
	return c > 0 and jsondecode(json) or loadstring('return '..string.gsub(json,'("(%w+)"%s-:)','%2='))()
end

a little test

http.request("http://www.twolivesleft.com/Codea/Talk/discussions/list.json",
	function(json)
		-- if we want to handle parse error
		-- local suc,data = pcall(jsonencode,json)
		local data = jsondecode(json)
		for _,post in ipairs(data.Announcements) do
			print(post.Name)
		end
    end)

There’s a nice Lua-based JSON encoder / decoder at

http://regex.info/blog/lua/json