lua对象json序列化,很简单,没做中文的unicode编码了

local function bool2json(v)
return v and "true" or "false";
end

local function string2json(s)
return table.concat({"\"", s, "\""});
end

local allowedkey={
["boolean"]=true,
["number"]=true,
["table"]=true,
}
local function table2json(tb)
local s={};
for k, v in next, tb do
local kind=type(k);
if not allowedkey[type(k)] then
error(_from("{kind}类型不能做为json格式数据key", kind));
end
table.push(s, lua2json(k), ":", lua2json(v), ",");
end
return table.concat(s);
end

local function number2json(num)
return tostring(num);
end

local lua2jsonfuncs={
["boolean"]=bool2json,
["number"]=number2json,
["table"]=table2json,
["string"]=string2json
}
function _G.lua2json(v)
local kind=type(v);
local func=lua2jsonfuncs[kind];
if not func then
error(_from("{kind}类型不能转化为json格式数据", kind));
end
return func(v);
end

--[[-----------test--------------
dump(lua2json(true));
dump(lua2json(false));
dump(lua2json("absd"));
dump(lua2json({a=true, b=1, c='fwef', d={a=true, b=1, c='ffef'}}));
dump(lua2json{1,2,4,3}) ]]

lua2json的更多相关文章

随机推荐

  1. [Functional Programming] Combine State Dependent Transactions with the State ADT (composeK to replace multi chian call)

    When developing a Finite State Machine, it is often necessary to apply multiple transitions in tande ...

  2. [Algorithms] Divide and Recurse Over an Array with Merge Sort in JavaScript

    Merge sort is a recursive sorting algorithm. If you don't understand recursion, I recommend finding ...

  3. 简易选项卡&&简易JS年历

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  4. Linux组件封装(四)使用RAII技术实现MutexLock自动化解锁

    我们不止一次写过这种代码: { mutex_.lock(); //XXX if(....) return; //XXX mutex_.unlock(); } 显然,这段代码中我们忘记了解锁.那么如何防 ...

  5. 怎样取消Macbook上顽固的开机启动项

    博主遇到的一个顽固启动项是Cisco Anyconnect.我仅仅是偶尔须要使用VPN.可是安装了Cisco Anyconnect之后,每次开机它都会启动,非常烦人. 1 通过系统设置 首先,博主希望 ...

  6. Singleton单例模式是最简单的设计模式,它的主要作用是保证在程序执行生命周期中,使用了单类模式的类仅仅能有一个实例对象存在。

                                                                                                        ...

  7. 1、硬件IO口配置;

    对于MTK TP驱动移植一般分为六部分: 1.硬件IO口配置: 2.TP驱动移植. 3.I2C通信: 4.中断触发: 5.数据上报: 6.虚拟按键. 硬件电路: 1.GPIO配置 打开 mediate ...

  8. js 根据所输内容生成助记码

      js生成与中文字符串相对映的拼音首字母串 CreateTime--2017年7月14日16:35:31Author:Marydon 需要工具js文件letter.js,代码如下: /** 作者:梅 ...

  9. mongoDB: cursor not found on server

    查询mongoDB集合数据更新,数据有400w多.我一次用cursor(游标)取1w,处理更新.程序在某段时间运行中遍历游标时发生异常! DBCursor cursor = tabColl.find( ...

  10. VB中的排序问题 15个

    首次接触VB,以下就先进行VB中的排序问题                   Dim a As Integer Dim b As Integer Dim c As Integer Dim d As ...