参考链接:
https://blog.csdn.net/liangneo/article/details/42461509
代码如下:
json2lua.py
1 import json 2 import types 3 import json 4 import os 5 import codecs 6 7 def space_str(layer): 8 lua_str = "" 9 for i in range(0,layer):10 lua_str += '\t'11 return lua_str12 13 def dic_to_lua_str(data,layer=0):14 d_type = type(data)15 if d_type is str:16 return "'" + data + "'"17 elif d_type is bool:18 if data:19 return 'true'20 else:21 return 'false'22 elif d_type is int or d_type is float:23 return str(data)24 elif d_type is list:25 lua_str = "{\n"26 lua_str += space_str(layer+1)27 for i in range(0,len(data)):28 lua_str += dic_to_lua_str(data[i],layer+1)29 if i < len(data)-1:30 lua_str += ','31 lua_str += '\n'32 lua_str += space_str(layer)33 lua_str += '}'34 return lua_str35 elif d_type is dict:36 lua_str = ''37 lua_str += "\n"38 lua_str += space_str(layer)39 lua_str += "{\n"40 data_len = len(data)41 data_count = 042 for k,v in data.items():43 data_count += 144 lua_str += space_str(layer+1)45 if type(k) is int:46 lua_str += '[' + str(k) + ']'47 else:48 lua_str += k 49 lua_str += ' = '50 try:51 lua_str += dic_to_lua_str(v,layer +1)52 if data_count < data_len:53 lua_str += ',\n'54 55 except Exception:56 print ('error in ',k,v)57 raise58 lua_str += '\n'59 lua_str += space_str(layer)60 lua_str += '}'61 return lua_str62 else:63 print (d_type , 'is error')64 return None65 66 def str_to_lua_table(jsonStr):67 data_dic = None68 try:69 data_dic = json.loads(jsonStr)70 except Exception:71 data_dic =[]72 else:73 pass74 finally:75 pass76 bytes = ''77 for it in dic_to_lua_str(data_dic):78 bytes += it79 return bytes80 81 def file_to_lua_file(jsonFile,luaFile):82 with codecs.open(luaFile,"w","utf-8") as luafile:83 with codecs.open(jsonFile,"r","utf-8") as jsonfile:84 luafile.write(str_to_lua_table(jsonfile.read()))
测试:
test.py
1 import excel2json 2 import json2lua 3 4 jsonStr = excel2json.excel2json("./xls/test.xls","./json/test.json",1,3) 5 # print(jsonStr) 6 7 # print(type({}),end='\n') 8 # print(type([]),end='\n') 9 # print(type(""),end='\n')10 # print(type(1),end='\n')11 # print(type(1.2),end='\n')12 # print(type(True),end='\n')13 # print(type(False),end='\n')14 # print(type(None),end='\n')15 print(json2lua.str_to_lua_table(jsonStr))16 json2lua.file_to_lua_file("./json/test.json","./lua/test.lua")
json文件
lua文件
posted on 2019-08-12 23:18 阅读( ...) 评论( ...) 收藏