python - 从 JSON 中提取时转义字符不起作用
问题描述
我正在尝试构建一个非常简单的代码 SQL 代码格式化程序,它从 JSON 对象中提取查询,目标是将最终输出复制到剪贴板。我还没有到剪贴板部分,因为我无法让 Python 解释转义字符。
print
函数用转义字符和所有打印整个东西,我不知道为什么。
import json
main_query = {"text": "SELECT\n * from test where id = 1\n LIMIT 10"}
query = str(json.dumps(main_query['text']).strip('"'))
print(query) # Not working
print('{}'.format(query)) # Not working either
"""
Output:
SELECT\n * from test where id = 1\n LIMIT 10
SELECT\n * from test where id = 1\n LIMIT 10
"""
解决方案
了解为什么会发生这种情况也很重要。
当您对字符串执行json.dumps()时,您将获得字符串的表示形式。
例如,如果你这样做print(repr(main_query["text]))
,你会得到这个输出:
SELECT \n * from test where id = 1 \n LIMIT 10
但是,不需要对包含换行符的字符串执行repr()或json.dumps并且您希望这些换行符被打印出来。
如果你只这样做:
import json
main_query = {"text": "SELECT \n * from test where id = 1 \n LIMIT 10"}
query = main_query['text'].strip('"')
print(query)
你会得到你想要的字符串:
SELECT
* from test where id = 1
LIMIT 10
推荐阅读
- azure - Video Indexer 每次上传都会创建新容器
- r - R中两个大数据框之间的不常见行
- forms - LibreOffice 基本搜索表单过滤器
- javascript - 在 MutationObserver 上返回 true
- mysql - 将行从一个表复制到另一个表时如何解决数据截断错误,两个表具有相同的模式?
- kotlin-multiplatform - 如何使用 Kotlin/native 生成依赖于另一个的 .framework?
- java - 在 Univocity Parser 中将 ResultSet 格式化为特定的 DecimalFormat
- apache - 始终在根目录而不是子目录中执行 index.php
- python - Zoom api 问题 - 访问令牌无效 - JWT
- python - 从列表中更新 json 列表