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

问题描述

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

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,data=json.dumps(payload))

另外,你需要用引号将 newpassword 括起来:

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

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

{
  "args": {},"data": "{\n    \"id\": 123,\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"
}