python 请求的 Json 变量中带有斜杠的文本

Text with slash into Json variable for python requests

在尝试从 API 检索数据时,我需要将包含斜线的文本传递到 Json 变量中。我尝试了很多方法,但在扫描字符串时不断收到错误 EOL。

    textSent = \"This is my text\"

    payload = """{
    \"language\": \"en\",
     \"text\": textSent
     }"""

   response = requests.request("POST", url, data=payload)

我的一些尝试包括:

'\"This is my text\"
"\"This is my text\""
r'\"This is my text\"

注意这个有效:

payload = """{
\"language\": \"en\",
 \"text\": \"This is my text\"
 }"""

你的问题是你没有终止你试图分配给 textSent 的字符串。您正在转义最后一个 ",这意味着这将是字符串的一部分,但因此您现在缺少 " 来告诉 Python 这是字符串的结尾。因此 Python 一直在搜索该字符,但由于您从未终止此代码行中的字符串,它在找到 " 之前到达了该行的末尾,因此 EOL。 要将此文本作为 JSON 发送,只需使用 json.dumps()。 请根据您的代码查看以下示例程序,它向您展示了两种将 \" 包含到您的字符串中并将它们作为 JSON 请求发送到 API 端点的方法正文

import json
import sys

import requests

# Possibility 1: here: use " to declare the string => " and \ must be escaped if they should be part of the string
textSentOnePossibility = "This is my text which contains \ slashes and \" quotation marks"
# Possibility 2: here: use ' to declare the string => " does not need to be escaped but \ must be escaped if it should be part of the string
textSentAnotherPossibility = 'This is my text which contains \ slashes and " quotation marks'
print(textSentOnePossibility)
print(textSentAnotherPossibility)

# build dictionary following the structure of your required JSON payload
payload_dict = {
    "language": "en",
    "text": textSentAnotherPossibility
}

# serialize to json
payload_json = json.dumps(payload_dict)

# make request (here: use postman echo API to to the actual request being sent)
resp = requests.post("https://postman-echo.com/post", data=payload_json)
if resp.status_code != 200:
    print("Request failed")
    sys.exit(1)
# print raw json that is returned from the API
print(resp.text)

预期输出:

This is my text which contains \ slashes and " quotation marks
This is my text which contains \ slashes and " quotation marks
{"args":{},"data":{"lang":"de","text":"This is my text which contains \ slashes and \" quotation marks"},"files":{},"form":{},"headers":{"x-forwarded-proto":"https","x-forwarded-port":"443","host":"postman-echo.com","x-amzn-trace-id":"Root=1-6227986c-6d094aed6d68bbd63c1c497e","content-length":"90","user-agent":"python-requests/2.27.1","accept-encoding":"gzip, deflate","accept":"*/*","content-type":"application/json"},"json":{"lang":"de","text":"This is my text which contains \ slashes and \" quotation marks"},"url":"https://postman-echo.com/post"}

编辑

根据您的评论,我认为您真正想要的只是 json.dumps(),它将 python in-memory 结构转换为相应的 JSON。没有必要自己fiddle 和"\ 等等。 使用 json.dumps() 应该就足够了。 以下程序将您在上面提供的工作字符串与我使用 json.dumps().

创建的工作字符串进行比较

Please note: I removed the newlines from your working string to get an exact match using == but other than that it is the string you provided.

import json

textSent = "This is my text"

# build dictionary following the structure of your required JSON payload
payload_dict = {
    "language": "en",
    "text": textSent
}
# the string you provided except that I removed the new lines
payload = """{\"language\": \"en\", \"text\": \"This is my text\"}"""

# serialize to json string
payload_json = json.dumps(payload_dict)

# the two texts are equal
print(payload_json)
print(payload)
print(payload_json == payload)

预期输出:

    {"language": "en", "text": "This is my text"}
    {"language": "en", "text": "This is my text"}
    True

如果您真的想生成类似于上面输入的字符串的内容,您只需 re-apply json.dumps() 两次即可。

import json

textSent = "This is my text"

# build dictionary following the structure of your required JSON payload
payload_dict = {
    "language": "en",
    "text": textSent
}

# apply json dumps twice
payload_json = json.dumps(json.dumps(payload_dict))

print(payload_json)

我曾经使用这种方法将 JSON 文档中的 JSON 文档作为字符串发送,但通常 API 不需要或不使用这种方法。

预期输出:

"{\"language\": \"en\", \"text\": \"This is my text\"}"

希望这就是您要找的。