Advertisement
Lanzr

json

Oct 19th, 2023 (edited)
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.15 KB | None | 0 0
  1. json = {}
  2. function json.table2json(t)
  3.     --将表格转换为json
  4.     local function serialize(tbl)
  5.         local tmp = {}
  6.         for k, v in pairs(tbl) do
  7.             local k_type = type(k)
  8.             local v_type = type(v)
  9.             local key = (k_type == "string" and "\"" .. k .. "\":") or (k_type == "number" and "")
  10.             local value = (v_type == "table" and serialize(v)) or (v_type == "boolean" and tostring(v)) or (v_type == "string" and "\"" .. v .. "\"") or (v_type == "number" and v)
  11.             tmp[#tmp + 1] = key and value and tostring(key) .. tostring(value) or nil
  12.         end
  13.         if table.maxn(tbl) == 0 then
  14.             return "{" .. table.concat(tmp, ",") .. "}"
  15.         else
  16.             return "[" .. table.concat(tmp, ",") .. "]"
  17.         end
  18.     end
  19.     assert(type(t) == "table")
  20.     return serialize(t)
  21. end
  22. function json.appendFile(fileName, content)
  23.     local f = assert(io.open(fileName, 'w'))
  24.     f:write(content)
  25.     f:close()
  26. end
  27.  
  28. function json.appendFile_Table(fileName, t)
  29.     local str = json.table2json(t)
  30.     local f = assert(io.open(fileName, 'w'))
  31.     f:write(str)
  32.     f:close()
  33. end
  34.  
  35.  
  36.  
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement