开发者

Parse JavaScript variable with Python [duplicate]

This question already has answers here: How to convert raw javascript object to a dictionary? (6 answers) Closed 8 months ago.

How can I 开发者_C百科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"],
}


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜