Last active
August 29, 2015 14:05
-
-
Save scythe/e62fb0408a98a38b7543 to your computer and use it in GitHub Desktop.
A JSON parser in LPeg.re
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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