Search code examples
pythondictionarylua

Converting .lua table to a python dictionary


I have this kind of input:

    sometable = {
        ["a"] = {
            "a1",
        },
        ["b"] = {
            "b1",
            ["b2"] = true,
        },
        ["c"] = {
            "c1",
            ["c2"] = true,
        },
    },

And would like to convert it to some dictionary I can work with in python - or basically, I just need to be able to read the data in this pattern:

print sometable[b][b2]

What is the best solution to this? I tried to do a bunch of replaces and convert it using ast, ie:

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)

The problem is that the output is:

{
 "a" : 
  {"a1", },
 "b" : 
  {"b1", "b2" : true,},
 "c" : 
  {"c1", "c2" : 1,},
}

The error (invalid syntax) is on {"b1", "b2" : true,},. Any suggestion?


Solution

  • Look at this package: 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}}