使用 python 在 JSON 负载中传递字符串

Pass string in JSON payload using python

我想将随机生成的密码传递给我的负载。这就是我的-

import requests
import json
import random
import string

#generate 12 character password
alphabet = string.ascii_letters + string.digits + '!@#%^*()'
newpassword = ''.join(random.choice(alphabet) for i in range(12))

url = "https://www.example.com"
payload = "{\n    \"id\": 123,\n    \"name\": \"John\",\n  \"itemValue\": "+newpassword+" \n}"
headers = {
    'Content-Type': 'application/json',
}
response = requests.put(url, headers=headers, data=json.dumps(payload))
print(response.text)

我没有得到想要的输出,因为它没有正确获取新密码字符串。 请指教

你的 payload 已经是一个 JSON 字符串,所以不需要调用 json.dumps(payload) ,只需要使用:

response = requests.put(url, headers=headers, data=payload)

当您的负载不是 JSON 字符串时,需要调用 json.dumps。例如:

payload = {"id": 123, "name": "John", "itemValue": newpassword}
requests.put(url, headers=headers, data=json.dumps(payload))

此外,您需要用引号将新密码括起来:

payload =  "{\n    \"id\": 123,\n    \"name\": \"John\",\n"
payload += "\"itemValue\": \"" + newpassword + "\" \n}"

为了测试它,我将您的 url 更改为“https://httpbin.org/put”,它工作正常。输出是:

{
  "args": {},
  "data": "{\n    \"id\": 123,\n    \"name\": \"John\",\n  \"itemValue\": \"Vj1YsqPRF3RC\" \n}",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Content-Length": "69",
    "Content-Type": "application/json",
    "Host": "httpbin.org",
    "User-Agent": "python-requests/2.25.1",
    "X-Amzn-Trace-Id": "Root=1-601e4aa5-2ec60b9839ba899e2cf3e0c9"
  },
  "json": {
    "id": 123,
    "itemValue": "Vj1YsqPRF3RC",
    "name": "John"
  },
  "origin": "13.110.54.43",
  "url": "https://httpbin.org/post"
}