Skip to content

Instantly share code, notes, and snippets.

@TripleDogDare
Created April 16, 2014 18:40
Show Gist options
  • Save TripleDogDare/10918698 to your computer and use it in GitHub Desktop.
Save TripleDogDare/10918698 to your computer and use it in GitHub Desktop.
JSON = {}
function JSON:new (o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function JSON:stringify(depthLimit, depth)
depthLimit = depthLimit or 10
depth = depth or 1
local temp = {}
local index = 1
local indent = string.rep("\t",depth)
local indentP = string.rep("\t",depth+1)
for i,v in pairs(self) do
if type(v)=="table" then
if getmetatable(v)==getmetatable(self) then
--object
temp[index] = string.format("%q: ",i) .. v:stringify(depthLimit,depth+1)
else
--array
temp[index] = string.format("%q: ",i) .. '[\n' .. indentP .. '"' .. table.concat(v,'",\n'..indentP..'"') .. '"\n' .. indent .. ']'
end
else
temp[index] = string.format("%q: %q",i, v)
end
index=index+1
end
return "{\n"..indent..table.concat(temp,",\n"..indent).."\n"..string.rep("\t",depth-1).."}"
end
function JSON:set(index,value)
self[index] = value
end
function JSON:append(index,value)
self[index] = self[index] or {}
self[index][#self[index]+1] = value
end
obj = JSON:new()
obj:set("thing",JSON:new())
obj["thing"]:set("number",5)
obj["thing"]:set("array",{"a","b","c","d","e"})
obj:set("foo","bar")
obj:append("otherArray","x")
obj:append("otherArray","y")
obj:append("otherArray","z")
print(obj["thing"]:stringify())
print(obj:stringify())
@kofalt
Copy link

kofalt commented Apr 16, 2014

go

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment