emi*_*ir0 3 python lua dictionary
我有这种输入:
sometable = {
["a"] = {
"a1",
},
["b"] = {
"b1",
["b2"] = true,
},
["c"] = {
"c1",
["c2"] = true,
},
},
Run Code Online (Sandbox Code Playgroud)
并想将其转换为我可以在python中使用的字典-或基本上,我只需要能够以这种模式读取数据:
print sometable[b][b2]
Run Code Online (Sandbox Code Playgroud)
最好的解决方案是什么?我试图做一堆替换并使用进行转换ast,即:
def make_dict(input): # just body, ie. without 'sometable'
input = input.replace("=", ":")
input = input.replace("[\"", "\"")
input = input.replace("\"]", "\"")
input = input.replace("\t", "")
input = input.replace("\n", "")
input = "{" + input + "}"
return ast.literal_eval(input)
Run Code Online (Sandbox Code Playgroud)
问题是输出是:
{
"a" :
{"a1", },
"b" :
{"b1", "b2" : true,},
"c" :
{"c1", "c2" : 1,},
}
Run Code Online (Sandbox Code Playgroud)
错误(invalid syntax)亮起{"b1", "b2" : true,},。有什么建议吗?
查看此包:https : //github.com/SirAnthony/slpp。
>>> from slpp import slpp as lua
>>> code = """{
["a"] = {
"a1",
},
["b"] = {
"b1",
["b2"] = true,
},
["c"] = {
"c1",
["c2"] = true,
},
}"""
>>> print(lua.decode(code))
{'a': ['a1'], 'c': {0: 'c1', 'c2': True}, 'b': {0: 'b1', 'b2': True}}
Run Code Online (Sandbox Code Playgroud)