【发布时间】:2020-12-04 20:03:11
【问题描述】:
所以我使用 Python 来获取 JSON 请求,并从中制作字典。现在我需要将它转换为 Lua,以便我可以将字典粘贴到我的 Lua 代码中;我无法将: 转换为=,因为有很多字典。
例如,打印时的 Python 字典是
{"key" : value}
而 Lua 表只接受{"key" = value}。
【问题讨论】:
标签: python arrays dictionary lua
所以我使用 Python 来获取 JSON 请求,并从中制作字典。现在我需要将它转换为 Lua,以便我可以将字典粘贴到我的 Lua 代码中;我无法将: 转换为=,因为有很多字典。
例如,打印时的 Python 字典是
{"key" : value}
而 Lua 表只接受{"key" = value}。
【问题讨论】:
标签: python arrays dictionary lua
lines = []
for key, value in your_dict.items():
lines.append(f'{"{key}"={value}} ')
with open("./dict.txt", "w"): as f:
f.write('\n'.join(lines))
【讨论】:
这是一个 hacky、脆弱的解决方案,因为 OP 说使用 JSON 库是不可能的。
目前尚不清楚 Python 字典中可能存储哪些值,但这些值很可能是字符串或其他字典。以下尝试处理嵌套字典,并将字符串值放在引号中。请注意,Lua 不会在表构造函数中的键周围使用引号。
# Python 3 code
d = { 'one': 1, 'two': 2, 'adict': { 'x': 'a', 'y': 'b'} }
def py_dict_to_lua_table (d):
lines = '{'
for k, v in d.items():
if isinstance(v, dict):
v = py_dict_to_lua_table(v)
elif isinstance(v, str):
v = f'"{v}"'
lines += f'{k} = {v},'
lines += '}'
return lines
lua_string = "my_lua_table = " + py_dict_to_lua_table(d)
with open('test.lua', 'w') as f:
f.write(lua_string)
然后,从命令行:
$ python3 convert.py
然后,来自 Lua:
$ lua -i test.lua
Lua 5.3.5 Copyright (C) 1994-2018 Lua.org, PUC-Rio
> dofile "../lua/lib/utils.lua"
> table.inspect(my_lua_table)
one = 1
adict =
y = b
x = a
two = 2
> my_lua_table.adict.y
b
请注意,如果 Python 字典包含不方便的值,例如数组,这是行不通的。 py_dict_to_lua_table 函数必须被扩充以将 Python 数组表示为 Lua 表(或你有什么)。如果可能的话,使用 JSON 解析库的另一个原因。
【讨论】:
你可以使用json.JSONEncoder:
from json import JSONEncoder
encoder = JSONEncoder(separators=[', ', ' = '])
dict_str = encoder.encode({'a': 1, 'b': {'c': 3, 'd': [4, 5]}})
print(dict_str)
输出:
{"a" = 1, "b" = {"c" = 3, "d" = [4, 5]}}
【讨论】: