【问题标题】:Python json.loads ValueError, expecting delimiterPython json.loads ValueError,需要分隔符
【发布时间】:2023-04-06 00:50:01
【问题描述】:

我将一个 postgres 表提取为 json。输出文件包含如下行:

{"data": {"test": 1, "hello": "I have \" !"}, "id": 4}

现在我需要使用json.loads 将它们加载到我的python 代码中,但是我收到了这个错误:

Traceback (most recent call last):
  File "test.py", line 33, in <module>
    print json.loads('''{"id": 4, "data": {"test": 1, "hello": "I have \" !"}}''')
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 381, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting , delimiter: line 1 column 50 (char 49)

我发现解决方法是将另一个\ 添加到\"。所以,如果我通过了

{"data": {"test": 1, "hello": "I have \\" !"}, "id": 4}

json.loads,我明白了:

{u'data': {u'test': 1, u'hello': u'I have " !'}, u'id': 4}

有没有办法在不添加额外的\ 的情况下做到这一点?比如向json.loads 传递参数之类的?

【问题讨论】:

  • 嘿伙计们,我有同样的问题任何有效的解决方案?

标签:
python
json
python-2.7