首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在多行JSON字符串中转义双引号?

如何在多行JSON字符串中转义双引号?
EN

Stack Overflow用户
提问于 2022-05-03 09:58:08
回答 1查看 183关注 0票数 0

我正在尝试运行以下代码,该代码将JSON字符串转换为Python:

代码语言:javascript
运行
复制
test = """
{"t":"\""}
"""
a=json.loads(test)

当我试图运行这段代码时,它会给出:

代码语言:javascript
运行
复制
---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
Input In [45], in <cell line: 4>()
      1 test = """
      2 {"t":"\""}
      3 """
----> 4 a=json.loads(test)
      5 a

File /usr/local/lib/python3.9/json/__init__.py:346, in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    341     s = s.decode(detect_encoding(s), 'surrogatepass')
    343 if (cls is None and object_hook is None and
    344         parse_int is None and parse_float is None and
    345         parse_constant is None and object_pairs_hook is None and not kw):
--> 346     return _default_decoder.decode(s)
    347 if cls is None:
    348     cls = JSONDecoder

File /usr/local/lib/python3.9/json/decoder.py:337, in JSONDecoder.decode(self, s, _w)
    332 def decode(self, s, _w=WHITESPACE.match):
    333     """Return the Python representation of ``s`` (a ``str`` instance
    334     containing a JSON document).
    335 
    336     """
--> 337     obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    338     end = _w(s, end).end()
    339     if end != len(s):

File /usr/local/lib/python3.9/json/decoder.py:353, in JSONDecoder.raw_decode(self, s, idx)
    344 """Decode a JSON document from ``s`` (a ``str`` beginning with
    345 a JSON document) and return a 2-tuple of the Python
    346 representation and the index in ``s`` where the document ended.
   (...)
    350 
    351 """
    352 try:
--> 353     obj, end = self.scan_once(s, idx)
    354 except StopIteration as err:
    355     raise JSONDecodeError("Expecting value", s, err.value) from None

JSONDecodeError: Expecting ',' delimiter: line 2 column 8 (char 8)

鉴于:

代码语言:javascript
运行
复制
test = """
{
  "t":"jjlsjdlk"
}
"""
a=json.loads(test)

效果很好。如何转义引号字符?

EN

回答 1

Stack Overflow用户

发布于 2022-05-03 10:18:22

这就是如何在"t"值中转义双引号的方法。

代码语言:javascript
运行
复制
test = r'{"t":"\""}'
a=json.loads(test)

如果您真的想要多行,请使用带有双反斜杠的简单字符串:

代码语言:javascript
运行
复制
test = '\
{\
"t": "\\""\
}\
'
a=json.loads(test)
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72097717

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档