python將json轉換成lua

廢話不多說,直接上代碼:

# -*- coding:utf-8 -*-
import json
import types
import sys
import os
import os.path
def space_str(layer):
	lua_str = ""
	for i in range(0,layer):
		lua_str += '\t'
	return lua_str
 
def dic_to_lua_str(data,layer=0):
	d_type = type(data)
	if  d_type is types.StringTypes or d_type is str or d_type is types.UnicodeType:
		return "'" + data + "'"
	elif d_type is types.BooleanType:
		if data:
			return 'true'
		else:
			return 'false'
	elif d_type is types.IntType or d_type is types.LongType or d_type is types.FloatType:
		return str(data)
	elif d_type is types.ListType:
		lua_str = "{\n"
		lua_str += space_str(layer+1)
		for i in range(0,len(data)):
			lua_str += dic_to_lua_str(data[i],layer+1)
			if i < len(data)-1:
				lua_str += ','
		lua_str += '\n'
		lua_str += space_str(layer)
		lua_str +=  '}'
		return lua_str
	elif d_type is types.DictType:
		lua_str = ''
		lua_str += "\n"
		lua_str += space_str(layer)
		lua_str += "{\n"
		data_len = len(data)
		data_count = 0
		for k,v in data.items():
			data_count += 1
			lua_str += space_str(layer+1)
			if type(k) is types.IntType:
				lua_str += '[' + str(k) + ']'
			else:
				lua_str += k 
			lua_str += ' = '
			try:
				lua_str += dic_to_lua_str(v,layer +1)
				if data_count < data_len:
					lua_str += ',\n'
 
			except Exception, e:
				print 'error in ',k,v
				raise
		lua_str += '\n'
		lua_str += space_str(layer)
		lua_str += '}'
		return lua_str
	else:
		print d_type , 'is error'
		return None

if __name__ == "__main__":
    rootdir = sys.argv[1]
    for parent,dirnames,filenames in os.walk(rootdir):
        for filename in filenames:
            extra_name = filename.split('.')[-1]
            if(str.find(extra_name,"json") == 0):
                dstfilename = os.path.join(parent,filename)
                with open(dstfilename) as file_obj:
                    content = file_obj.read()
                    dest_file = os.path.join(parent,filename.split('.')[0] + ".lua")
                    pf = open(dest_file,"w")
                    pf.write(filename.split('.')[0] + " = " + dic_to_lua_str(json.loads(content)))

通過以上代碼就能批量將json轉換成lua了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章