Python json.loads ValueError,需要定界符 [英] Python json.loads ValueError, expecting delimiter
问题描述
我正在将Postgres表提取为json.输出文件包含以下行:
I am extracting a postgres table as json. The output file contains lines like:
{"data": {"test": 1, "hello": "I have \" !"}, "id": 4}
现在我需要使用json.loads
将它们加载到我的python代码中,但出现此错误:
Now I need to load them in my python code using json.loads
, but I get this error:
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)
我发现解决方法是向\"
添加另一个\
.所以,如果我通过
I figured out the fix is to add another \
to \"
. So, if I pass
{"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
之类的东西?
Is there a way to do this without adding the extra \
? Like passing a parameter to json.loads
or something?
推荐答案
您可以指定所谓的原始字符串":
You can specify so called "raw strings":
>>> print r'{"data": {"test": 1, "hello": "I have \" !"}, "id": 4}'
{"data": {"test": 1, "hello": "I have \" !"}, "id": 4}
他们不解释反斜杠.
通常的字符串将\"
更改为"
,因此您可以在字符串中使用"
字符,这些字符本身受双引号限制:
Usual strings change \"
to "
, so you can have "
characters in strings that are themselves limited by double quotes:
>>> "foo\"bar"
'foo"bar'
因此,从\"
到"
的转换不是由json.loads
完成,而是由Python本身完成.
So the transformation from \"
to "
is not done by json.loads
, but by Python itself.
这篇关于Python json.loads ValueError,需要定界符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!