forked from Roblox/graphql-lua
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson.lua
More file actions
79 lines (74 loc) · 1.71 KB
/
json.lua
File metadata and controls
79 lines (74 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
-- from this GitHub gist: https://gist.github.com/tylerneylon/59f4bcf316be525b30ab
local json = {}
local function kind_of(obj)
if type(obj) ~= "table" then
return type(obj)
end
local i = 1
for _ in pairs(obj) do
if obj[i] ~= nil then
i = i + 1
else
return "table"
end
end
if i == 1 then
return "table"
else
return "array"
end
end
local function escape_str(s: string)
local in_char = { "\\", '"', "/", "\b", "\f", "\n", "\r", "\t" }
local out_char = { "\\", '"', "/", "b", "f", "n", "r", "t" }
for i, c in ipairs(in_char) do
s = s:gsub(c, "\\" .. out_char[i])
end
return s
end
function json.stringify(obj: any, as_key: boolean?)
local s = {} -- We'll build the string as an array of strings to be concatenated.
local kind = kind_of(obj) -- This is 'array' if it's an array or type(obj) otherwise.
if kind == "array" then
if as_key then
error("Can't encode array as key.")
end
s[#s + 1] = "["
for i, val in ipairs(obj) do
if i > 1 then
s[#s + 1] = ", "
end
s[#s + 1] = json.stringify(val)
end
s[#s + 1] = "]"
elseif kind == "table" then
if as_key then
error("Can't encode table as key.")
end
s[#s + 1] = "{"
for k, v in pairs(obj) do
if #s > 1 then
s[#s + 1] = ", "
end
s[#s + 1] = json.stringify(k, true)
s[#s + 1] = ":"
s[#s + 1] = json.stringify(v)
end
s[#s + 1] = "}"
elseif kind == "string" then
return '"' .. escape_str(obj) .. '"'
elseif kind == "number" then
if as_key then
return '"' .. tostring(obj) .. '"'
end
return tostring(obj)
elseif kind == "boolean" then
return tostring(obj)
elseif kind == "nil" then
return "null"
else
error("Unjsonifiable type: " .. kind .. ".")
end
return table.concat(s)
end
return json