Advertisement
CloneTrooper1019

DecodeJSON.lua

Dec 23rd, 2014
471
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.07 KB | None | 0 0
  1. function DecodeJSON(input)
  2.     -- This function tries to convert the syntax of a JSON table into a Lua Table,
  3.     -- and dumps it as a table using loadstring.
  4.     local str = "return "
  5.     while #input > 0 do
  6.         local chunk = string.sub(input,1,1)
  7.         input = string.sub(input,2)
  8.         if chunk == [["]] then
  9.             local quoteEnd = string.find(input,[["]])
  10.             if not quoteEnd then
  11.                 print(input)
  12.                 error()
  13.             end
  14.             local key = string.sub(input,1,quoteEnd-1)
  15.             input = string.sub(input,#key+2)
  16.             if not tonumber(key) then
  17.                 -- See if we could use the string alone as a key for a table without brackets or quotes
  18.                 -- If not, then we need to put quotes around it.
  19.                 local noQuotes = pcall(function ()
  20.                     assert(loadstring("t = {" .. key .." = 0}"))
  21.                 end)
  22.                 if not noQuotes then
  23.                     key = [["]] .. key .. [["]]
  24.                 end
  25.             end
  26.             str = str .. key
  27.         elseif chunk == "[" then
  28.             str = str .. "{"
  29.         elseif chunk == "]" then
  30.             str = str .. "}"
  31.         elseif chunk == ":" then
  32.             str = str .. " = "
  33.         else
  34.             str = str .. chunk
  35.         end
  36.     end
  37.     return loadstring(str)()
  38. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement