1. 程式人生 > >table序列化成json格式檔案

table序列化成json格式檔案

在遊戲開中我們經常會有將資料轉換為一個位元組流或者字元流的需求,然後將其儲存到一個檔案或者通過網路連線傳送出去,
在lua中對於儲存在table中的資料我們可以簡單序列化成json檔案儲存到本地

--無環table序列化為json格式儲存到檔案
local file = io.open("1.json", "w")
if(file == nil) then
    print("open file 1.txt fail")
end

function getTableLen(tab)
    local len = 0
    for k, v in pairs(tab) do
        len = len + 1
    end
    return len
end

function serialize(pTable, indent)
    indent = indent or 0
    local spaceStr = string.rep("  ", indent)
    if(type(pTable) == "number") then
        file:write(pTable)
    elseif(type(pTable) == "string") then
        file:write(string.format("%q", pTable))
    elseif(type(pTable) == "table") then
        indent = indent + 1
        spaceStr = string.rep("  ", indent)
        file:write("{\n")
        local length = getTableLen(pTable)
        local index = 0
        for k, v in pairs(pTable) do
            index = index + 1
            file:write(string.format("%s", spaceStr));
            serialize(k, indent)
            file:write(" : ");
            serialize(v, indent)
            if(index < length) then
                file:write(",\n")
            else
                file:write("\n")
            end
        end
        local space = string.rep("  ", indent - 1)
        file:write(string.format("%s}", space))
    else
        error("cannot serialize a " .. type(pTable))
    end
end
local temp = {
    a = 1,
    b = 'helloworld "one"',
    c = {
            dic = {key = 12, value = "class"},
            name = "zxh",
            sec = {
                m = "sikd",
                n = 90,
            }
    }
}
serialize(temp)
file:close()

生成的json檔案內容如下: