Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion

JSON decoder snippet

toffertoffer Mod
edited April 2014 in Code Sharing Posts: 151

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

Comments

Sign In or Register to comment.