Table 2 Json And Json 2 Table (Mostly for debugging) with pretty print
WolfGang Senizen
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
Log In
WolfGang Senizen
Working with SamanthaTekcat Resident yesterday
We came up with functions similar to
llJsonSetValue
and llJsonGetValue
setTableVal
local function setTableVal(tab,path,val)
for k,v in pairs(path) do
if k == #path then break end
if type(tab[v]) == nil then tab[v] = {} end
tab = tab[v]
if type(tab) ~= "table" then return false end
end
tab[path[#path]] = val
end
And
getTableVal
local function getTableVal(tab,path)
for k,v in pairs(path) do
tab = tab[v]
if tab == nil then return nil end
end
return tab
end
As helper lua functions for those
They aren't identical as they modify the table in place, and don't quite support the
JSON_DELETE
type of functionality, you can pass nil
but that's a bit different