如何使用lua中的模式序列化/反序列化表格

我有以下表格:

local obj = {
    firstname = "John",
    lastname  = "Bush",
    age = 22,
    height = 186,
    friends = {
        { firstname = "Paul", lastname = "Graham", age = 20, height = 178 },
        { firstname = "Gianou", lastname = "Kwnstantina", age = 25, height = 172 }
    },
    bodies = { 4, 3, 10 }
}

我想将其转换为这个:(插入数据库时)

local tuple = {
    'John', 'Bush', 22, 186, { { 'Paul', 'Graham', 20, 178 }, { 'Gianou', 'Kwnstantina', 25, 172 } }, { 4, 3, 10 }
}

用以下代码生成:

function encode(schema, data)
    local array = {}

    function rec(arr, schema, d)

        for i, field in ipairs(schema) do

            arr[i] = {}
            if field.type == "array" and type(field.items) == "table" then

                for it, piece in ipairs(d[field.name]) do
                    arr[i][it] = {}
                    rec(arr[i][it], field.items, piece)
                end

            else

                arr[i] = d[field.name]

            end

        end
    end

    rec(array, schema, data)

    return array
end

我的问题是,我想重构数据以恢复它的初始形式。我在其他语言中找到了一些可以做到这一点的工具,但问题是它们将数据转换为二进制,而我只想得到那个数组。

为了能够重构,我需要像模式这样的东西:

local schema = {
    { name = "firstname", type = "string" },
    { name = "lastname", type = "string" },
    { name = "age", type = "int" },
    { name = "height", type = "int" },
    { name = "friends", type = "array", items = {
        { name = "firstname", type = "string" },
        { name = "lastname", type = "string" },
        { name = "age", type = "int" },
        { name = "height", type = "int" }
    }},
    { name = "bodies", type = "array", items = "int"}
}

我发现只需检索值即可轻松将其编码,但是能够验证和解码似乎相当困难,计算机科学中是否有这种操作的概念(名称),或者是否有我可以学习的库(它需要使用一个模式)? 我需要一个可以搜索的关键字......

谢谢!

编辑:只需反转编码,我发现解码很简单。

function decode(schema, data)
    local obj = {}

    function rec(object, sch, d)
        for i, field in ipairs(sch) do

            if field.type == "array" and type(field.items) == "table" then
                object[field.name] = {}

                for it, piece in ipairs(d[i]) do

                    object[field.name][it] = {}

                    rec(object[field.name][it], field.items, piece)
                end

            else
                object[field.name] = d[i]
            end

        end
    end

    rec(obj, schema, data)

    return obj
end

我仍然喜欢在代码和我可以找到关于此类信息的更多信息方面提出建议。

当前版本:https://pastebin.com/Ub4vZ0GU

点赞