美文网首页
json转lua的小工具

json转lua的小工具

作者: 流飞飞FW | 来源:发表于2020-11-19 09:29 被阅读0次
目录结构:
图片.png
Readme.txt:

1.run.cmd可转换当前目录下所有json文件。
2.也可单独拖动json文件到json2lua.py转换。

json2lua.py代码:
# coding=utf-8
import re
import sys

#读取文件
path = "test.json"
if(len(sys.argv) > 1):
    path = sys.argv[1]

f = open(path)
content = f.read()
f.close()

content = re.sub(r'\[', '{', content)

content = re.sub(r']', '}', content)

content = re.sub(r'//', '--', content)

newList = []

#找到所有键
obj = re.compile( r'"[^,]*?:')
list_1 = obj.findall(content)

for s in list_1:
    tmp = '[' + s
    tmp = re.sub(r'"\s*?:', '\"] =', tmp)
    newList.append(tmp)

#将处理后的字符串替换回去
for i in range(len(list_1)):
    content = content.replace(list_1[i], newList[i])

#修正特殊情况,如"key" : "value", "key" : ...
#content = re.sub(r'=\s*?\[\"', '= \"', content)
#content = re.sub(r',\s*\"', ', [\"', content)
#print(content)

#write to a lua file
filename = re.sub(r'\..*$','', path)
f = open(filename + '.lua', 'w')
f.write(content)
f.close()
print("output --> " + filename + '.lua')
run.cmd代码:
@echo off
set DIR=%~dp0
cd /d "%DIR%"
setlocal enabledelayedexpansion
for  %%i in (*.json) do ( 
      python %DIR%json2lua.py "%%i"
)
echo "Done"
PAUSE

相关文章

网友评论

      本文标题:json转lua的小工具

      本文链接:https://www.haomeiwen.com/subject/girkiktx.html