Python在解析json时中断了字符\“

2024-05-16 10:58:27 发布

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

我试图用转义符(我猜是某种类型)解析json字符串

{
    "publisher": "\"O'Reilly Media, Inc.\""
}

如果我从字符串中删除字符\",解析器的分析效果很好

不同解析器引发的异常是

json

^{pr2}$

ujson

ValueError: Unexpected character in found when decoding object value

如何使解析器转义这些字符?在

更新: enter image description here在本例中,ps.json作为ujson导入

enter image description here

这是我的ide显示的

逗号只是意外添加的,json末尾没有尾随逗号,json有效

enter image description here

字符串定义。在


Tags: 字符串json解析器类型字符mediapublisherinc
2条回答

您的JSON无效。如果您对JSON对象有疑问,可以使用JSONlint验证它们。在你的情况下,你有一个目标

{
"publisher": "\"O'Reilly Media, Inc.\"",
}

你有一个额外的逗号,表示有别的东西要来了。所以JSONlint产生了

Parse error on line 2: ...edia, Inc.\"", } -^ Expecting 'STRING'

这将帮助你找到错误所在。在

删除的逗号

^{pr2}$

收益率

Valid JSON

更新:我将保留关于JSONlint的内容,因为它可能在将来对其他人有所帮助。至于格式良好的JSON对象,我已经

import json

d = {
    "publisher": "\"O'Reilly Media, Inc.\""
    }

print "Here is your string parsed."
print(json.dumps(d))

屈服

Here is your string parsed. {"publisher": "\"O'Reilly Media, Inc.\""}

Process finished with exit code 0

几乎可以肯定的是,您没有正确定义转义反斜杠。如果正确定义字符串,JSON解析就可以了

>>> import json
>>> json_str = r'''
... {
...     "publisher": "\"O'Reilly Media, Inc.\""
... }
... '''  # raw string to prevent the \" from being interpreted by Python
>>> json.loads(json_str)
{u'publisher': u'"O\'Reilly Media, Inc."'}

注意,我使用了一个原始字符串文本来定义Python中的字符串;如果我没有,Python将解释\",并插入一个常规的"。您必须将反斜杠加倍,否则:

^{pr2}$

将解析后的Python结构重新编码回JSON会显示反斜杠重新出现,字符串的repr()输出使用相同的双反斜杠:

>>> json.dumps(json.loads(json_str))
'{"publisher": "\\"O\'Reilly Media, Inc.\\""}'
>>> print json.dumps(json.loads(json_str))
{"publisher": "\"O'Reilly Media, Inc.\""}

如果您没有转义\转义,您将以未转义引号结束:

>>> json_str_improper = '''
... {
...     "publisher": "\"O'Reilly Media, Inc.\""
... }
... '''
>>> print json_str_improper

{
    "publisher": ""O'Reilly Media, Inc.""
}

>>> json.loads(json_str_improper)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting , delimiter: line 3 column 20 (char 22)

注意,\"序列现在被打印成",反斜杠消失了!在

相关问题 更多 >