簡體   English   中英

從 JSON 提取時,轉義字符不起作用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM