我想分析JavaScript對象的代碼,它包含巨大的JavaScript數組並將其轉換爲帶有列表的Python字典。最快的方法來將JavaScript對象/數組轉換爲Python字典/列表
在我使用PyYaml的那一刻,但沒有直接的工作,因爲它不能處理連續的逗號(例如,它打破了關於「[,,, 0,]」以:預期節點內容,但發現',')。所以我把它們取代了,但是這一切都很慢。我想知道您是否有任何人知道更好更快的方式來做到這一點。 JSON解碼不起作用,因爲JavaScript代碼也不是JSON有效。
這是我使用的代碼,如上所述,與js_obj爲例:
js_obj = "{index: '37',data: [, 1, 2, 3,,,]}"
def repl(match):
content = re.sub(" ", "",match.group(0))
length = len(content) - 1
result = ''
if content[0] == '[':
result = '[""'
length -= 1
after = ','
if content[-1] == ']':
length -= 1
after += '""]'
return result + (',""' * length) + after
py_dict = yaml.load(re.sub('\[? *(, *)+\]?', repl, js_obj))
請看:http://stackoverflow.com/questions/10057375/python-parsing-json-like-javascript-data-structures-w-consecutive-commas – alecxe
是否http://slimit.readthedocs.org/ en/latest /#iterate-over-modify-a-javascript-ast-and-pretty-print-it help? – vsr