Last active
June 23, 2024 03:32
-
-
Save opsJson/e42c1ece18abc07c70298704fea0927d to your computer and use it in GitHub Desktop.
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
function jsonParse(str) | |
if not str then return nil end | |
str = str:match("^%s*(.-)%s*$") | |
if #str == 0 then return nil end | |
local t = str:sub(1, 1) | |
str = str:sub(2, -2):match("^%s*(.-)%s*$") .. ',' | |
local obj = {} | |
local depth = 0 | |
local last = 0 | |
local insideString = false | |
for i=1, #str do | |
local c = str:sub(i, i) | |
if c == '[' or c == '{' then | |
depth = depth + 1 | |
elseif c == ']' or c == '}' then | |
depth = depth - 1 | |
elseif c == '\"' and str:sub(i-1, i-1) ~= '\\' then | |
insideString = not insideString | |
end | |
if c == ',' and depth == 0 and not insideString then | |
local segment = str:sub(last, i-1) | |
last = i+1 | |
local key, value | |
if t == '{' then | |
key, value = segment:match('"(.-)"%s*:%s*(.+)') | |
if not value then value = "" end | |
if not key then key = -1 end | |
elseif t == '[' then | |
value = segment:match("^%s*(.-)%s*$") | |
end | |
local valueType = value:sub(1, 1) | |
if valueType == '\"' then | |
value = value:match('^"(.-)"$') | |
elseif valueType == '{' or valueType == '[' then | |
value = jsonParse(value) | |
else | |
if value == "true" then | |
value = true | |
elseif value == "false" then | |
value = false | |
elseif value == "null" then | |
value = nil | |
else | |
value = tonumber(value) or value | |
end | |
end | |
if t == '{' then | |
obj[key] = value | |
elseif t == '[' then | |
table.insert(obj, value) | |
end | |
end | |
end | |
return obj | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment