解析不使用字符串作为属性名的javascript对象声明(使用python和BeautifulSoup)

2024-09-28 03:17:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做的事情与this user was doing非常相似:尝试将javascript对象声明加载到python字典中。但是,与该用户不同的是,属性名没有用引号括起来。在

>>> 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标记,那就太棒了:

^{pr2}$

但是,我没有。我该怎么解决这个问题呢?也许它可以归结为一个简单的正则表达式?在

编辑:Martijn写的This regex让我半途而废,如果在我的一些示例数据中出现的大括号后面有尾随空格,它就不起作用了,例如{ num1: 1383241561141, num2: 1000}'


Tags: inpypackageslinesiteusersfileend
2条回答

RSON这样的一些库支持解析所谓的“宽松”JSON符号。在

取决于实际的密钥,并且如果您不关心安全问题(永远不要在外部输入上使用这个),那么eval也可能会给您一个正常工作的字典。在

在js中实现这一点的一个简单方法是:

'{num1: 1383241561141, num2: 1000}'   // the string
  .trim()                             // remove whitespace
  .slice(1,-1)                        // remove endcap braces
  .trim()                             // remove whitespace
  .split(/\s*,\s*/).map(function(a){  // loop through each comma section names as a
     var p=a.split(/\s*:\s*/);        // split section into key/val segments
     this[p[0]]=p[1];                 // assign val to collection under key
     return this;                     // return collection
},{})[0];                             // grab the return once (same on each index)

此例程返回一个活动对象,其字符串如下:

^{pr2}$

注意字符串编号,如果需要,可以再次循环对象并将这些键编号(val)返回实数。在

相关问题 更多 >

    热门问题