Parse JavaScript variable with Python

匿名 (未验证) 提交于 2019-12-03 03:02:02

问题:

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:

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



回答2:

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



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!