Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 345
emihir0 Avatar asked Jul 05 '26 19:07

emihir0


1 Answers

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}}
like image 190
skovorodkin Avatar answered Jul 08 '26 09:07

skovorodkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!