您的位置:首页 > 编程语言 > Lua

lua2json

2013-11-26 21:56 344 查看
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}) ]]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: