Skip to content

Instantly share code, notes, and snippets.

@scythe
Last active August 29, 2015 14:05
Show Gist options
  • Save scythe/e62fb0408a98a38b7543 to your computer and use it in GitHub Desktop.
Save scythe/e62fb0408a98a38b7543 to your computer and use it in GitHub Desktop.
A JSON parser in LPeg.re
re = require "re"
local function condense(keyvals)
local obj = {}
for i = 1, #keyvals do
obj[keyvals[i][1]] = keyvals[i][2]
end
return obj
end
--Nulls are represented by this function. It should work, I guess?
local function null() return nil end
return re.compile([[
value <- object / array / string / number / word
object <- {| '{' ws (keyval (ws ',' ws keyval)*)? ws '}' |} -> condense
keyval <- {| key ws ':' ws value |}
key <- string
array <- {| '[' ws (value (ws ',' ws value)*)? ws ']' |}
string <- '"' ({| (eseq / char) * |} -> concat) '"'
eseq <- '\' {.}
char <- {[^"]}
number <- { '-'? ((istr ('.' istr? ('e+' istr)?)?) / ('.' istr)) } -> numval
istr <- %d+
word <- { "true" / "false" / "null" } -> wordval
ws <- (%s / %nl)*
]], {
condense = condense
,wordval = {["true"] = true, ["false"] = false, null = null}
,numval = tonumber
,concat = table.concat
} )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment