views:

125

answers:

2

How can I convert a Javascript variable (not JSON format) into a python variable?

Example Javascript variable:

{
    title: "TITLE",
    name: "NAME",
    active: false,
    info: {
        key1: "value1",
        dict1: {
            sub_key1: "sub_value1",
            sub_key2: "sub_value2",
        },
        dict2: {
            sub_key3: "sub_value3",
            sub_key4: "sub_value4",
            sub_key5: "sub_value5"
        },
    },
    list1: ["element1", "element2", "element2"],
}
+1  A: 

This format looks just like the input in this question. Try adapting the pyparsing parser I posted there.

Paul McGuire
+2  A: 

Convert it to JSON and read it in python.

I really do not understand what is the problem?

e.g. JSON.stringify gives

{"title":"TITLE","name":"NAME","active":false,"info":{"key1":"value1","dict1":{"sub_key1":"sub_value1","sub_key2":"sub_value2"},"dict2":{"sub_key3":"sub_value3","sub_key4":"sub_value4","sub_key5":"sub_value5"}},"list1":["element1","element2","element2"]}

Which can be read by python json module, so question is where from you are getting javascript and why can't you convert it to JSON?

Edit: if the source of javascript if totally out of your control, you can use javascript as a command line scripting language e.g. spidermonkey (used in firefox), rhino, V8 (used in google chrome) or on windows WSH. Using javascript interpreter you can modify javascript , stringify it and then process it with python if needed.

It is better to user already implemented and tested interpreter than to build one by yourselves.

You can also try python-spidermonkey

Anurag Uniyal
@Anurag Uniyal, how can I stringify a Javascript variable to JSON string in Python? I cannot control the format of the source variable. It appears exactly as listed above in a .html file.
jack
@jack, see the edit.
Anurag Uniyal