lua语言json与table互转,简单方法

2023-10-27

使用方法

1、json转table

luaJson.json2lua(tab)

2、table转json

luaJson.table2json(str)

这个原理就是是逐个解析字符串,同样可以解析json、xml,具体代码如下

--这里解析json作为示例
luaJson = {}
local function json2true(str, from, to)
    return true, from + 3
end

local function json2false(str, from, to)
    return false, from + 4
end

local function json2null(str, from, to)
    return nil, from + 3
end

local function json2nan(str, from, to)
    return nul, from + 2
end

local numberchars = {
    ['-'] = true,
    ['+'] = true,
    ['.'] = true,
    ['0'] = true,
    ['1'] = true,
    ['2'] = true,
    ['3'] = true,
    ['4'] = true,
    ['5'] = true,
    ['6'] = true,
    ['7'] = true,
    ['8'] = true,
    ['9'] = true,
}

local function json2number(str, from, to)
    local i = from + 1
    while (i <= to) do
        local char = string.sub(str, i, i)
        if not numberchars[char] then
            break
        end
        i = i + 1
    end
    local num = tonumber(string.sub(str, from, i - 1))
    if not num then
        Log("red", 'json格式错误,不正确的数字, 错误位置:', from)
    end
    return num, i - 1
end

local function json2string(str, from, to)
    local ignor = false
    for i = from + 1, to do
        local char = string.sub(str, i, i)
        if not ignor then
            if char == '\"' then
                return string.sub(str, from + 1, i - 1), i
            elseif char == '\\' then
                ignor = true
            end
        else
            ignor = false
        end
    end
    Log("red", 'json格式错误,字符串没有找到结尾, 错误位置:{from}', from)
end

local function json2array(str, from, to)
    local result = {}
    from = from or 1
    local pos = from + 1
    local to = to or string.len(str)
    while (pos <= to) do
        local char = string.sub(str, pos, pos)
        if char == '\"' then
            result[#result + 1], pos = json2string(str, pos, to)
        --[[    elseif char == ' ' then
        
        elseif char == ':' then
        
        elseif char == ',' then]]
        elseif char == '[' then
            result[#result + 1], pos = json2array(str, pos, to)
        elseif char == '{' then
            result[#result + 1], pos = luaJson.json2table(str, pos, to)
        elseif char == ']' then
            return result, pos
        elseif (char == 'f' or char == 'F') then
            result[#result + 1], pos = json2false(str, pos, to)
        elseif (char == 't' or char == 'T') then
            result[#result + 1], pos = json2true(str, pos, to)
        elseif (char == 'n') then
            result[#result + 1], pos = json2null(str, pos, to)
        elseif (char == 'N') then
            result[#result + 1], pos = json2nan(str, pos, to)
        elseif numberchars[char] then
            result[#result + 1], pos = json2number(str, pos, to)
        end
        pos = pos + 1
    end
    Log("red", 'json格式错误,表没有找到结尾, 错误位置:{from}', from)
end

local function string2json(key, value)
    return string.format("\"%s\":\"%s\",", key, value)
end

local function number2json(key, value)
    return string.format("\"%s\":%s,", key, value)
end

local function boolean2json(key, value)
    value = value == nil and false or value
    return string.format("\"%s\":%s,", key, tostring(value))
end

local function array2json(key, value)
    local str = "["
    for k, v in pairs(value) do
        str = str .. luaJson.table2json(v) .. ","
    end
    str = string.sub(str, 1, string.len(str) - 1) .. "]"
    return string.format("\"%s\":%s,", key, str)
end

local function isArrayTable(t)
    
    if type(t) ~= "table" then
        return false
    end
    
    local n = #t
    for i, v in pairs(t) do
        if type(i) ~= "number" then
            return false
        end
        
        if i > n then
            return false
        end
    end
    
    return true
end

local function table2json(key, value)
    if isArrayTable(value) then
        return array2json(key, value)
    end
    local tableStr = luaJson.table2json(value)
    return string.format("\"%s\":%s,", key, tableStr)
end



function luaJson.json2table(str, from, to)
    local result = {}
    from = from or 1
    local pos = from + 1
    local to = to or string.len(str)
    local key
    while (pos <= to) do
        local char = string.sub(str, pos, pos)
        --Log("yellow", pos, "-->", char)
        if char == '\"' then
            if not key then
                key, pos = json2string(str, pos, to)
            else
                result[key], pos = json2string(str, pos, to)
                key = nil
            end
        --[[    elseif char == ' ' then
        
        elseif char == ':' then
        
        elseif char == ',' then]]
        elseif char == '[' then
            if not key then
                key, pos = json2array(str, pos, to)
            else
                result[key], pos = json2array(str, pos, to)
                key = nil
            end
        elseif char == '{' then
            if not key then
                key, pos = luaJson.json2table(str, pos, to)
            else
                result[key], pos = luaJson.json2table(str, pos, to)
                key = nil
            end
        elseif char == '}' then
            return result, pos
        elseif (char == 'f' or char == 'F') then
            result[key], pos = json2false(str, pos, to)
            key = nil
        elseif (char == 't' or char == 'T') then
            result[key], pos = json2true(str, pos, to)
            key = nil
        elseif (char == 'n') then
            result[key], pos = json2null(str, pos, to)
            key = nil
        elseif (char == 'N') then
            result[key], pos = json2nan(str, pos, to)
            key = nil
        elseif numberchars[char] then
            if not key then
                key, pos = json2number(str, pos, to)
            else
                result[key], pos = json2number(str, pos, to)
                key = nil
            end
        end
        pos = pos + 1
    end
    Log("red", 'json格式错误,表没有找到结尾, 错误位置:{from}', from)
end

--json格式中表示字符串不能使用单引号
local jsonfuncs = {
    ['\"'] = json2string,
    ['['] = json2array,
    ['{'] = luaJson.json2table,
    ['f'] = json2false,
    ['F'] = json2false,
    ['t'] = json2true,
    ['T'] = json2true,
}

function luaJson.json2lua(str)
    local char = string.sub(str, 1, 1)
    local func = jsonfuncs[char]
    if func then
        return func(str, 1, string.len(str))
    end
    if numberchars[char] then
        return json2number(str, 1, string.len(str))
    end
end

function luaJson.table2json(tab)
    local str = "{"
    for k, v in pairs(tab) do
        if type(v) == "string" then
            str = str .. string2json(k, v)
        elseif type(v) == "number" then
            str = str .. number2json(k, v)
        elseif type(v) == "boolean" then
            str = str .. boolean2json(k, v)
        elseif type(v) == "table" then
            str = str .. table2json(k, v)
        end
    end
    str = string.sub(str, 1, string.len(str) - 1)
    return str .. "}"
end

return luaJson
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

lua语言json与table互转,简单方法 的相关文章

随机推荐

  • Pymol入门教程--基础

    Pymol入门教程 基础 软件界面介绍 内置demo介绍 打开PyMOL 点击1 1菜单窗口的Wizard菜单 然后点击Demo gt Representations然后在2 3对象窗口和2 4模式窗口之间会出现各种示例 Represent
  • Docker-Compose的安装

    一 什么是Docker Compose Compose项目来源于之前的fig项目 使用python语言编写 与docker swarm配合度很高 Compose 是 Docker 容器进行编排的工具 定义和运行多容器的应用 可以一条命令启动
  • IDEA插件安装以及一些不错的插件的推荐

    IDEA有自己庞大的插件支持 来丰富生态 现在一个好用点的工具如果没有点插件都不好意思 当然了 微信除外 因为人家会告你 一 插件的安装 IDEA的插件安装和别的IDE工具 比如eclipse或者vscode的位置都差不多 还是具体说一下
  • TensorFlow二元-多类-多标签分类示例

    探索不同类型的分类模型 使用 TensorFlow 构建二元 多类和多标签分类器 二元分类 简述 逻辑回归 二元交叉熵 二元分类架构 案例 逻辑回归预测获胜团队 多类分类 简述 Softmax 函数 分类交叉熵 多类分类架构 案例 预测航天
  • Jenkins CI、CD入门操作

    基于Jenkins拉取GitLab指定发行版本的SpringBoot代码进行构建发布到生产环境实现CD实现持续部署 准备测试项目 准备一个简单的Spring boot 项目 Jenkins新建任务 Jenkins关联Gitlab自动拉取最新
  • 如果一个人真的懂你

    一辈子 遇见一个真正读懂你的人 真的很难 人的一生中会遇到几十甚至上百万个人 其中能和你打招呼 称得上是朋友的人就更少 而在这么多人当中 却很有可能连一个真正懂你的人都没有 有些人 就算相识再久 也无法成为知己 有些人 即使你说了千句 他都
  • 基于错误信息的SQL盲注

    何谓盲注 在SQL注入基础一文中介绍了SQL注入的基本原理 可以轻易注入的原因是知道SQL拼接代码是怎么写的 很多情况下 很难甚至无法知道对方的SQL拼接语句是怎么写的 这里情况下需要做尝试 分析代码是采用何种拼接结构 然后再写个万能注入公
  • python docx 表格样式的设置修改表格列宽

    我的需求是设置表格的列宽和高度 之前的代码使用网上找的方法 table cell y x width Cm 4 无论怎么修改都是无效的 最后正确的代码是 col table columns 1 col width Inches 5
  • 修改mt4服务器地址,修改mt4服务器地址

    修改mt4服务器地址 内容精选 换一换 云平台支持修改主网卡的私有IP地址 具体操作请参见本节内容 如需修改扩展网卡的私有IP地址 请删除网卡 并挂载新网卡 云服务器已关机 如果网卡绑定了虚拟IP或者DNAT规则 需要先解绑 如果网卡上有I
  • [译] APT分析报告:03.OpBlueRaven揭露APT组织Fin7/Carbanak(上)Tirion恶意软件

    这是作者新开的一个专栏 主要翻译国外知名的安全厂商APT报告文章 了解它们的安全技术 学习它们溯源APT组织的方法 希望对您有所帮助 前文分享了钓鱼邮件网址混淆URL逃避检测 这篇文章将介绍APT组织Fin7 Carbanak的Tirion
  • 什么浏览器好用稳定速度快?

    什么浏览器好用稳定速度快 说到浏览器 不知道你们是否有这样的困惑和烦恼 浏览器换了一款又一款 内存大就不说了 体验总是不尽人意 经常弹出一些莫名其妙的资讯 还会出现卡住 奔溃 网页打开不完全 打开速度慢等情况 就拿我最近用的两款360来说吧
  • Nginx+lua实现秒杀系统架构

    能今天做好的事就不要等到明天 以梦为马 学习趁年华 文章目录 前言 一 秒杀业务特点 1 瞬时高并发 2 热点数据 3 读多写少 二 技术难点 1 数据一致性 2 库存超卖 三 秒杀注意事项 1 数据预热 2 请求承载 3 请求拦截 四 微
  • 重新理解Linux交叉编译及编译流程

    参考书籍 1 编译原理 2 嵌入式Linux应用开发 文章目录 一 交叉编译背景 二 gcc和arm linux gcc的常用选项 1 查询gcc帮助 2 常用gcc选项介绍 3 生成一个可执行文件的三种方法 二 交叉编译的四个流程及实例说
  • iOS编程基础-OC(六)-专家级技巧:使用ARC

    该系列文章系个人读书笔记及总结性内容 任何组织和个人不得转载进行商业活动 第6章 专家级技巧 使用ARC 本章是第一部分的最后一章 本章介绍ARC内存管理中的细微之处 如直接桥接对象使用ARC的方法 6 1 ARC和对象所有权 我们已经知道
  • 快排-java

    快排总结 分区方法 3个while 递归使用排序方法 使用了分治法 挖坑赋值法 package cn com import java util Arrays public class QuickSort public static void
  • 虚拟机上CentOS 7关闭防火墙操作

    虚拟机上CentOS 7关闭防火墙操作 1 首先查看防火墙的状态 使用的命令为 service iptables status 提示 Unit iptables service could not be found 解决方案 还原传统的管理
  • sprintf实例

    include
  • Unity热更新 ILRuntime 从零开始 HelloWorld(二)

    自从我凌晨两点放下喝醉的小姐姐回家写博客之后 小姐姐对我愈发的崇拜了 约我今晚一块学习ILRuntime 带好身份证 我这一想必须要未雨绸缪 安排 选了一个全市最好的网吧 斥巨资通宵5元 请小姐姐一块学习 一起记录下学习内容 这是这一系列文
  • 数字频率计设计

    FPGA教程目录 MATLAB教程目录 设计任务与要求 1 设计任务 设计并实现一个数字频率计 2 基本要求 测频率范围 10Hz 10K Hz 为保证测量精度分为三个频段 10Hz 100 Hz 100Hz 1K Hz 1 K Hz 10
  • lua语言json与table互转,简单方法

    使用方法 1 json转table luaJson json2lua tab 2 table转json luaJson table2json str 这个原理就是是逐个解析字符串 同样可以解析json xml 具体代码如下 这里解析json