Table 2 Json
A quick and dirty method for dumping a table into a string
function table2json(tbl,depth)
if depth == true then depth = 1 end
local set = {}
local obj = false;
local frst = 0
for k,v in pairs(tbl) do
if k ~= (frst + 1) then
obj = true
break
end
frst = frst + 1
end
for k , v in pairs(tbl) do
local t = type(v)
if t == "number" then v = `{v}`
elseif v == nil then v = `null`
elseif t == "table" then v = table2json(v,depth and depth+1 or false)
elseif t == "function" then v = `"function<{debug.info(v,"n")}>"`
else v = `"{v}"` end
if obj then
v = `"{k}":{v}`
end
set[#set+1] = v
end
local sep = ","
if obj then
if depth then
sep = ",\n"
sep = sep .. string.rep(" ",depth*2)
set = sep:sub(2) .. table.concat(set,sep) .. sep:sub(2,#sep - 4)
else
set = table.concat(set,sep)
end
return `\{{set}\}`
end
return `[{table.concat(set,sep)}]`
end
can be called like this
local tbl = {`a`,2,uuid("677bf9a4-bba5-4cf9-a4ad-4802a0f7ef46"),{`b`,`c`,{`d`,`e`,vector(1,1,1)}},a=`7`,{x=1,y=2,z=3},ll.Say}
ll.OwnerSay(table2json(tbl))
ll.OwnerSay(table2json(tbl,true))
passing true or a number into the second argument enables indentation / pretty print
Json 2 Table
a crude v1 of json 2 table
local function json2table(json)
local tb = ll.Json2List(json)
for k,v in pairs(tb) do
if type(v) == "string" then
local t = ll.JsonValueType(v,{});
if t == utf8.char(0xFDD2) then
tb[k] = json2table(v)
elseif t == utf8.char(0xFDD1) then
local obj = json2table(v)
v = {}
for i = 1, #obj, 2 do
v[obj[i]] = obj[i+1]
end
tb[k] = v
end
end
end
return tb
end