lua2json

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}) ]]

posted on 2013-11-26 21:56  marcher  阅读(511)  评论(0编辑  收藏  举报

导航