import json
import types
import os,sys
import sys
from Tkinter import *
import datetime
import time
import Tkinter, Tkconstants, tkFileDialog
import tkMessageBox
reload(sys)
sys.setdefaultencoding('utf-8')
def isJsonStr(newstr):
try:
json.loads(newstr)
except Exception as e:
#except ValueError:
return False
else:
return True
def addSpace(layer):
luaStr = ""
for i in range(0,layer):
luaStr += '\t'
return luaStr
def parsJsonObj(jsonObj,layer=0):
jsonObjType = type(jsonObj)
#字符串类型
if jsonObjType is types.StringTypes or jsonObjType is str or jsonObjType is types.UnicodeType:
#支持在json中再遇到json字符串时,继续解析json字符串
if isJsonStr(jsonObj):
luaStr = ''
luaStr += parsJsonObj(json.loads(jsonObj),layer+1)
return luaStr
else:
newstr = jsonObj.replace('\n', '\\n').replace('\t', '\\t').replace('"', '\\"').replace("'", "\\'")
#return "'" + newstr + "'"
return '"' + newstr +'"'
#数组类型
elif jsonObjType is types.ListType:
luaStr = "{\n"
luaStr += addSpace(layer+1)
for i in range(0,len(jsonObj)):
luaStr += parsJsonObj(jsonObj[i],layer+1)
if i < len(jsonObj)-1:
luaStr += ','
luaStr += '\n'
luaStr += addSpace(layer)
luaStr += '}'
return luaStr
elif jsonObjType is types.BooleanType:
if jsonObj:
return 'true'
else:
return 'false'
#数字类型
elif jsonObjType is types.IntType or jsonObjType is types.LongType or jsonObjType is types.FloatType:
jsonObjstr = str(jsonObj)
return str(jsonObj)
#字典类型
elif jsonObjType is types.DictType:
luaStr = ''
luaStr += "\n"
luaStr += addSpace(layer)
luaStr += "{\n"
jsonObjlen = len(jsonObj)
jsonObjcount = 0
for k,v in jsonObj.items():
jsonObjcount += 1
luaStr += addSpace(layer+1)
if type(k) is types.IntType or str.isdigit(str(k)) == True:
luaStr += '[' + k + ']'
else:
#print('is not int type : ' + str(k))
#那些以数字开头,又不是数字的key值非法,当字符串处理,
#比如 0nb、345nb、 34-45
if str.isdigit(str(str(k)[0]))==True:
luaStr += "['"+str(k)+"']"
else:
#普通键值
luaStr += k
luaStr += ' = '
try:
luaStr += parsJsonObj(v,layer +1)
if jsonObjcount < jsonObjlen:
luaStr += ',\n'
except Exception, e:
print 'error in ',k,v
raise
luaStr += '\n'
luaStr += addSpace(layer)
luaStr += '}'
return luaStr
else:
print jsonObjType , 'is error'
return None
def genLuaFile(genfileName,tableName,jsonStr):
try:
newdata = json.loads(jsonStr)
except Exception as e:
#except ValueError:
tkMessageBox.showinfo('提示', '遇到错误的json格式: \n ' + str(e))
return
luatableJson = parsJsonObj(newdata)
luagendir = luadir.get().replace('\\', '/')
if os.path.exists(luagendir) == False:
os.mkdir(luagendir)
newluafile = luagendir +'/'+genfileName
if os.path.exists(newluafile):
os.remove(newluafile)
with open(newluafile, 'a') as f:
f.write('return {\n')
f.write(tableName + " = " + luatableJson)
f.write('\n}')
f.close()
def genMyLua(jsonroot, jsonfile):
genfileName = jsonfile.replace('.json', '.lua')
jsonfilesdir = jsonroot+'/'+jsonfile
text = " "
with open(jsonfilesdir, 'r') as f:
try:
jsontext = f.read().decode('utf-8')
except Exception as e:
tkMessageBox.showinfo('提示', '读取json文件出错:\n '+str(e))
return
finally:
pass
genLuaFile(genfileName, 'data', jsontext)
f.close()
#===================================================================================
def findJsonFilesPath():
pathname=tkFileDialog.askdirectory()
if pathname != '':
pathname = pathname.replace('/','\\')
jsondir.delete(0, len(jsondir.get()))
jsondir.insert(END, pathname)
if pathname != '':
luadir.delete(0, len(luadir.get()))
luadir.insert(END, pathname+'\LuaTable')
def findGenLuaDir():
luapath=tkFileDialog.askdirectory()
if luapath != '':
luadir.delete(0, len(luadir.get()))
luadir.insert(END, luapath.replace('/','\\'))
def genLuaTable():
jsonroot = jsondir.get().replace('\\','/')
if jsonroot == '':
tkMessageBox.showinfo('提示', '你好, %s' % '请输入json文件根路径')
newluadir = luadir.get().replace('\\','/')
if os.path.exists(newluadir) == False:
os.mkdir(newluadir)
if newluadir == '' or os.path.exists(newluadir) == False:
tkMessageBox.showinfo('提示', '你好, %s' % '生成lua路径无效')
progressTips.config(text='正在生成.....')
ls = os.listdir(jsonroot)
jsonfs = []
for l in ls:
if len(l) < 5:
return
if l[-5:] == '.json':
jsonfs.append(l)
pass
for fn in jsonfs:
genMyLua(jsonroot, fn)
print(fn)
luadirls = os.listdir(newluadir)
luafs = []
for f in luadirls:
if f[-4:] =='.lua' and f.find('GameDataList') < 0:
luafs.append(f.replace('.lua', ''))
genLualistFile(newluadir, luafs)
progressTips.config(text='')
tkMessageBox.showinfo('提示', '生成结束')
os.system("explorer.exe %s" % newluadir.replace('/', '\\'))
def genLualistFile(luadir, luafs):
lualistfile = luadir+'/GameDataList.lua'
if os.path.exists(lualistfile):
os.remove(lualistfile)
with open(lualistfile, 'a') as f:
content = 'local function InitGameData(reqdir)'+'\n'
content = content + '\treturn {'
for luaf in luafs:
#name = require dir..'/'..f
content = content + '\n\t\t'
content = content + luaf + ' = require (' + 'reqdir.."/'+luaf+'"),'
pass
#去除最后一个逗号
content = content.rstrip(',')
#生成返回表
#content = content + '\n\n\t'
content = content +'\n\t}'
content = content + '\nend\n'
content = content + 'return InitGameData'
f.write(content)
f.close()
root = Tk()
root.title(unicode('json文件生成lua表工具','utf-8'))
#发送按钮事件
#创建几个frame作为容器
root.geometry('600x500')
frame01 = Frame(width=750, height=470)
#button_sendmsg = Button(frame01, text=unicode('发送','utf-8'), command=sendmessage)
#使用grid设置各个容器位置
frame01.grid(row=0, column=0, padx=2, pady=5)
frame01.grid_propagate(0)
#button_sendmsg.grid(sticky=E)
jsondirdesc = Label(frame01, width = 20, text = '输入json文件根路径:')
jsondir = Entry(frame01, width = 50)
findButton = Button(frame01, text=' 查找', command=findJsonFilesPath)
genLabel = Label(frame01, text='生成lua路径', width=50)
luadir = Entry(frame01, width = 50)
findgenBtn = Button(frame01, text=' 查找', command=findGenLuaDir)
genBtn = Button(frame01, text='生成Lua表文件', command=g
没有合适的资源?快使用搜索试试~ 我知道了~
json转lua-table工具
共10个文件
json:8个
lua:1个
py:1个
1.该资源内容由用户上传,如若侵权请联系客服进行举报
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
2.虚拟产品一经售出概不退款(资源遇到问题,请及时私信上传者)
版权申诉
5星 · 超过95%的资源 3 下载量 18 浏览量
2022-06-15
14:34:30
上传
评论
收藏 18KB RAR 举报
温馨提示
通过执行python脚本(jsonToLua.py)
资源推荐
资源详情
资源评论
收起资源包目录
json转lua工具.rar (10个子文件)
json转lua工具
celldata1.json 557B
table.json 183B
model.json 194KB
datahead1.json 424B
test.json 247B
LuaTable
fiter.json 52B
JsonToLua.py 9KB
celldata.json 1KB
luatable.lua 848B
datahead.json 2KB
共 10 条
- 1
阿奇博尔德
- 粉丝: 0
- 资源: 12
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
- 1
- 2
- 3
前往页