forked from schteppe/remote-physics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.lua
46 lines (42 loc) · 1004 Bytes
/
json.lua
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
-- simple table-to-json convert.
-- @todo add array support
function table.json(t)
-- Converts a number to string and removes trailing zeros. Saves some bytes
function num(n)
return string.gsub(string.gsub(string.format("%f",n),"0+$",""),"%.$",".0");
end
if type(t)=="number" then
return num(t)
end
if type(t)=="string" then
return "\""..t.."\""
end
-- check if all keys are numbers
local isarray = true
for key,val in pairs(t) do
if type(key)~="number" then
isarray = false
break
end
end
if isarray then
local json = "["
local del = ""
for key,val in pairs(t) do
json = json .. del .. table.json(val)
del = ","
end
return json .."]"
else
local json = "{"
local del = ""
for key,val in pairs(t) do
if type(key) == "number" then
key = key -1
end
json = json .. del .. "\"" .. key .. "\":" .. table.json(val)
del = ","
end
return json .."}"
end
end