[英]Fastest way to convert JavaScript object/array to Python dict/list
I'm trying to parse the code of JavaScript objects that hold huge JavaScript arrays and convert it to a Python dictionary with lists. 我正在尝试解析包含巨大JavaScript数组的JavaScript对象的代码,并将其转换为带有列表的Python字典。
At the moment I'm using PyYaml, but that didn't work directly, as it can't handle consecutive commas (eg it breaks on '[,,,0,]' with: expected the node content, but found ',' ). 目前,我正在使用PyYaml,但这不能直接使用,因为它不能处理连续的逗号(例如,它以',,, 0,]开头,其结尾是: 期望节点内容,但是找到了', ' )。 So I substituted these out, but this is all very slow.
所以我将它们替换掉了,但这一切都非常缓慢。 I'm wondering if any of you know of a better and faster way to do this.
我想知道你们中是否有人知道一种更好更快的方法。 JSON decode doesn't work as JavaScript code isn't JSON valid either.
JSON解码不起作用,因为JavaScript代码也不是JSON无效。
This is the code I'm using, explained above, with js_obj as example: 这是我正在使用的代码,如上所述,以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))
You probably should write data from JavaScript using JSON, and then read it into Python in JSON. 您可能应该使用JSON从JavaScript写入数据,然后将其读入JSON中的Python。 YAML is OK, but I tend to prefer JSON over YAML;
YAML可以,但是我倾向于使用JSON而不是YAML。 JSON is more consistent.
JSON更一致。
If you must parse the JavaScript, you might want to look into pyparsing or similar. 如果必须解析JavaScript,则可能需要研究pyparsing或类似方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.