Created
July 2, 2023 03:42
-
-
Save Vurv78/0f37bf6820a611d331daa1292cefcc36 to your computer and use it in GitHub Desktop.
Tiny JSON parser in Lua.
This file contains 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
-- JSON parser originally from qjson.lua | |
local function decode(json --[[@param json string]]) ---@return table | |
local ptr = 0 | |
local function consume(pattern --[[@param pattern string]]) ---@return string? | |
local start = json:find("^%S", ptr) | |
if start then ptr = start end | |
local start, finish, match = json:find(pattern, ptr) | |
if start then | |
ptr = finish + 1 | |
return match or true | |
end | |
end | |
local object, array | |
local function number() return tonumber(consume("^(%-?%d+%.%d+)") or consume("^(%-?%d+)")) end | |
local function bool() return consume("^(true)") or consume("^(false)") end | |
local function string() return consume("^\"([^\"]*)\"") end | |
local function value() return object() or string() or number() or bool() or array() end | |
function object() | |
if consume("^{") then | |
local fields = {} | |
while true do | |
if consume("^}") then return fields end | |
local key = assert(string(), "Expected field for table") | |
assert(consume("^:")) | |
fields[key] = assert(value(), "Expected value for field " .. key) | |
consume("^,") | |
end | |
end | |
end | |
function array() | |
if consume("^%[") then | |
local values = {} | |
while true do | |
if consume("^%]") then return values end | |
values[#values + 1] = assert(value(), "Expected value for field #" .. #values + 1) | |
consume("^,") | |
end | |
end | |
end | |
return object() or array() | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment