问题描述
我正在做与类似的操作该用户正在做的:尝试将javascript对象声明加载到python字典中.但是,与该用户不同,属性名称不包含在引号中.
I'm doing something very similar to what this user was doing: trying to load a javascript object declaration into a python dictionary. However, unlike that user, the property names aren't enclosed in quotes.
>>> simplejson.loads('{num1: 1383241561141, num2: 1000}')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/lalalal/site-packages/simplejson/__init__.py", line 385, in loads
return _default_decoder.decode(s)
File "/Users/lalalal/site-packages/simplejson/decoder.py", line 402, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Users/lalalal/site-packages/simplejson/decoder.py", line 418, in raw_decode
obj, end = self.scan_once(s, idx)
simplejson.decoder.JSONDecodeError: Expecting property name: line 1 column 1 (char 1)
如果我使用正确的JSON表示法,那就太好了
It'd be just splendid if I had the correct JSON notation:
>>> simplejson.loads('{"num1": 1383241561141, "num2": 1000}')
{'num1': 1383241561141, 'num2': 1000}
但是,我没有.我该如何解决?也许归结为正则表达式这么简单?
But, I don't. How can I work around this? Maybe it comes down to something as simple as a regex?
编辑: Martijn编写的此正则表达式到了一半,而实际上却没有.如果某些示例数据中的花括号后面有空格,则无法正常工作,例如{ num1: 1383241561141, num2: 1000}'
Edit: This regex that Martijn wrote has me halfway there, it just doesn't work if I have trailing whitespace after the braces which happens in some of my example data, e.g. { num1: 1383241561141, num2: 1000}'
推荐答案
某些库,例如 RSON 支持解析所谓的轻松" JSON表示法.
Some libraries like RSON support parsing the so-called "relaxed" JSON notation.
取决于实际的键,并且如果您不关心安全隐患(请不要在外部输入上使用此键),eval
可能还会为您提供功能正常的字典.
Depending on the actual keys, and if you don't care about the security implications (never use this on external input), eval
may give you a functioning dictionary as well.
这篇关于解析不使用字符串作为属性名称的javascript对象声明(使用python和BeautifulSoup)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!