首页 > 解决方案 > 从 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
"""

标签: pythonjson

解决方案


了解为什么会发生这种情况也很重要。

当您对字符串执行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

推荐阅读