难以理解 JSON 转义字符
我对编程很陌生,最近深入研究了Python 中的 JSON 转义和特殊字符主题。我知道如何转义双引号。例如:
导入 json
data = json.loads('{"Test": "In \\"quotation\\" 标记"}')
print( data)
returns(as a "dict"): {'Test': 'In "quotation" matches'}
但我无法理解其他特殊字符的含义使用方式如下:\b、\n、\、 \f 等...
有人可以向我展示一些代码示例,这些其他特殊转义字符将在何处以及如何使用,例如上面的 json.loads 函数。我将非常感激。谢谢
I'm quite new to programming and recently have dived into the topic of JSON Escape and special characters in Python. I understand how to escape double quotation marks. For example:
import json
data = json.loads('{"Test": "In \\"quotation\\" marks"}')
print(data)
returns(as a "dict"): {'Test': 'In "quotation" marks'}
But I can't wrap my head around how the other special characters would be used like: \b, \n, \, \f etc...
Could someone please show me some examples of code where and how those other special escape characters would be used in, say for example, a json.loads functions like above. I'd be very grateful. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JSON 字符串必须用双引号引起来;因此,您需要转义双引号才能将其包含在 JSON 字符串中。
但是,您还需要转义 Python 字符串文字中的反斜杠,以便在 JSON 值中获取文字反斜杠。您可以按照问题中所示的方式执行此操作:
或者使用原始字符串文字
部分混淆来自于 JSON 字符串值和 Python 字符串文字可能看起来相同这一事实。例如,由换行符组成的 JSON 字符串看起来像
定义由换行符组成的字符串的 Python 字符串文字也看起来像
定义包含 JSON 字符串的字符串的 Python 字符串文字由换行符组成的则可以是
或者
JSON strings must be double quoted; as such, you need to escape a double quote in order to include it in a JSON string.
However, you also need to escape the backslash in the Python string literal in order to get a literal backslash in the JSON value. You can do that as you show in your question:
or by using a raw string literal
Part of the confusion comes from the fact that JSON string values and Python string literals can look identical. For example, a JSON string that consists of a linefeed would look like
and a Python string literal defining a string that consists of a linefeed would also look like
A Python string literal defining a string that contains a JSON string consisting of a line feed would then be either
or
没关系。我想通了。我的问题是,当我执行
data = json.loads('{"Test": "In quote \\nmarks"}')
print(data)
时会返回: {'Test': 'In quote \n matches '} 我试图理解为什么它显示 \n 而不是实际的新行
我意识到转义仅在您查看时才会显示对于给定键的值。例如,
print(data["Test"]) 返回
In quote
marks
与 data = json.loads( '{"Test": "In "quotation" \\bmarks"}')
返回 = 在引号中
Nevermind. I figured it out. My problem was that when I was doing
data = json.loads('{"Test": "In quotation \\n marks"}')
print(data)
it would return: {'Test': 'In quotation \n marks '} and I was trying to understand why it shows \n instead of an actual new line
I realized the escapes only show up when you look for value of a given key. So for example,
print(data["Test"]) returned
In quotation
marks
same thing for data = json.loads('{"Test": "In "quotation" \\bmarks"}')
returns = In quotationmarks