tubular

JSON in LPEG re

Aug 29th, 2013
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.65 KB | None | 0 0
  1. require "re" -- no shit sherlock
  2.  
  3. -- this is the table that holds all the \substitutions
  4. -- it could easily be hardcoded into descape() but why bother
  5. descapetable = {
  6.   ['\\\\'] = '\\',
  7.   ['\\"'] = '"', ['\\/'] = '/',
  8.   ['\\t'] = '\9', ['\\n'] = '\10',
  9.   ['\\f'] = '\12', ['\\r'] = '\13',
  10. }
  11.  
  12. -- this function does the unescaping in strings
  13. -- you could do this within the PEG using substitution captures
  14. -- (at least, for everything besides the unicode)
  15. -- but i just said fuck it and moved on with the bot
  16. function descape (str)
  17.   local tab = {}
  18.  
  19.   -- unicode support
  20.   -- str = str:gsub('\\u(%x+)', function (num) end)
  21.  
  22.   -- other escapes
  23.   for c in str:gmatch'\\?.' do
  24.     if c == '\\b' then
  25.       tab[#tab] = nil
  26.     else
  27.       tab[1+#tab] = descapetable[c] or c
  28.     end
  29.   end
  30.  
  31.   return table.concat(tab)
  32. end
  33.  
  34. -- json:match(str) decodes str from json into a table
  35. -- note: both {objects} and [arrays] are translated to lua tables
  36. json = re.compile([[
  37.   value <- %s* ( object / array / string / {number} / ('true' / 'false') -> bool / 'null' -> null ) %s*
  38.   key <- %s* string %s*
  39.   object <- '{' ( key ':' value ','? )* -> {} -> object '}'
  40.   array <- '[' ( value ','? )* -> {} ']'
  41.   string <- '"' { ( [^"\] / {escape} )* } -> unesc '"'
  42.  escape <- '\' ( ["\/bfnrt] / 'u' %x^-4 )
  43.  number <- '-'? ( '0' / [1-9] %d* ) ( '.' %d+ )? ( [eE] [+-]? %d+ )?
  44. ]], {
  45.  bool = function (s) return s == 'true' end,
  46.  null = function () return nil end,
  47.  unesc = descape,
  48.  object = function (tab)
  49.    -- this is probably a little hackish
  50.    for i=1,#tab,2 do
  51.      tab[tab[i]], tab[i], tab[i+1] = tab[i+1]
  52.    end
  53.    return tab
  54.  end,
  55. })
Advertisement
Add Comment
Please, Sign In to add comment