参考链接:
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_str 12 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_str 35 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 = 0 42 for k,v in data.items(): 43 data_count += 1 44 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 raise 58 lua_str += '\n' 59 lua_str += space_str(layer) 60 lua_str += '}' 61 return lua_str 62 else: 63 print (d_type , 'is error') 64 return None 65 66 def str_to_lua_table(jsonStr): 67 data_dic = None 68 try: 69 data_dic = json.loads(jsonStr) 70 except Exception: 71 data_dic =[] 72 else: 73 pass 74 finally: 75 pass 76 bytes = '' 77 for it in dic_to_lua_str(data_dic): 78 bytes += it 79 return bytes 80 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文件
分类:
Unity工具
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?