[英]Escape characters not working when extracted from JSON
I am trying to build a very simple code SQL code formatter, which extracts the query from a JSON object and the goal is to copy the final output to the clipboard. 我还没有到剪贴板部分,因为我无法让 Python 解释转义字符。
print
function 用转义字符和所有字符打印整个内容,我不知道为什么。
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]))
,你会得到这个 output:
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
试试这个:
main_query = {"text": "SELECT\n * from test where id = 1\n LIMIT 10"}
print(main_query["text"])
SELECT
* from test where id = 1
LIMIT 10
import json
import re
main_query = {"text": "SELECT\n * from test where id = 1\n LIMIT 10"}
query = main_query['text']
print(re.sub('\n',' ',query))
使用这个伙伴,列表和循环打印实施
import json
main_query = {"text": "SELECT\n * from test where id = 1\n LIMIT 10"}
query = str(json.dumps(main_query['text']).strip('"'))
for word in query.split('\\n'):
print(word)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.