先分词,再解析,少写了语法检查
module( "json_to_lua", package.seeall )
--##############################################################################
--# 模块接口
--##############################################################################
-- json字符串转lua table
function JsonStrToLuaTable( szJsonStr )
local tWords = SplitWord( szJsonStr )
-- 此处应该加一个语法检查的
-- CheckSyntax( tWords )
local ResultObj = CreateObjectByWords( tWords )
return ResultObj
end
-- lua table转json
function LuaTableToJsonStr( tTable, nTabCnt )
nTabCnt = nTabCnt or 0
local szJsonStr = "\n"
assert( type( tTable ) == "table", "tTable is not a table." )
local szTab = ""
for i = 1, nTabCnt do
szTab = szTab .. '\t'
end
local szKeyType = nil
for key, value in pairs( tTable ) do
if szKeyType == nil then
szKeyType = type( key )
if szKeyType ~= "string" and szKeyType ~= "number" then
-- 处理不了其他类型的key
return nil
end
end
-- 处理key,key类型不一致,转换失败
if type( key ) ~= szKeyType then
return nil
end
szJsonStr = szJsonStr .. '\t' .. szTab
if szKeyType == "string" then
szJsonStr = szJsonStr .. string.format( "\"%s\" = ", EscDecode( key ) )
end
-- 处理value
if type( value ) == "table" then
szJsonStr = szJsonStr .. LuaTableToJsonStr( value, nTabCnt + 1 ) .. ",\n"
else
if type( value ) == 'string' then
value = '"' .. EscDecode( value ) .. '"'
end
szJsonStr = szJsonStr .. string.format( "%s,\n", value )
end
end
if szJsonStr == '\n' then szTab = ''; szJsonStr = '' end
if szKeyType == "string" then
return "{" .. szJsonStr .. szTab .. '}'
else
return "[" .. szJsonStr .. szTab .. ']'
end
end
-- 文件中读json文件并转成Lua table
function JsonFileToLuaTable( szJsonFileName )
local JsonFileObj = io<