Type : Module
Recommended place for it : Replicated Storage
What for / Name : SafeJson
Script content :
-- Json handler
local SafeJson = {}
function SafeJson.encode(value)
local t = typeof(value)
if t == "string" then
return SafeJson._str(value)
elseif t == "number" then
if value ~= value or math.abs(value) == math.huge then return "null" end
return tostring(value)
elseif t == "boolean" then
return value and "true" or "false"
elseif t == "nil" then
return "null"
elseif t == "table" then
local n = 0
for _ in pairs(value) do n = n + 1 end
if n == #value and n > 0 then
local p = {}
for i = 1, #value do p[i] = SafeJson.encode(value[i]) end
return "[" .. table.concat(p, ",") .. "]"
else
local p = {}
for k, v in pairs(value) do
if typeof(k) == "string" then
table.insert(p, SafeJson._str(k) .. ":" .. SafeJson.encode(v))
end
end
return "{" .. table.concat(p, ",") .. "}"
end
end
return "null"
end
function SafeJson._str(s)
local p = {}
local i = 1
while i <= #s do
local b = string.byte(s, i)
if b == 34 then table.insert(p, '\\"')
elseif b == 92 then table.insert(p, "\\\\")
elseif b == 8 then table.insert(p, "\\b")
elseif b == 12 then table.insert(p, "\\f")
elseif b == 10 then table.insert(p, "\\n")
elseif b == 13 then table.insert(p, "\\r")
elseif b == 9 then table.insert(p, "\\t")
elseif b < 32 then table.insert(p, string.format("\\u%04x", b))
else table.insert(p, string.char(b))
end
i = i + 1
end
return '"' .. table.concat(p) .. '"'
end
function SafeJson.decode(str)
return game:GetService("HttpService"):JSONDecode(str)
end
print("[SafeJson] Loaded json support table .")
return SafeJson
Enjoy , Hope it is useful ! ![]()