Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python在JSON负载中传递字符串_Python_Json_Payload - Fatal编程技术网

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

使用python在JSON负载中传递字符串,python,json,payload,Python,Json,Payload,我想将随机生成的密码传递给我的有效负载。这就是我所拥有的- 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

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

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)
我没有得到所需的输出,因为它没有正确使用新密码字符串。
请告知。

您的负载已经是一个JSON字符串,因此无需调用JSON.dumps(负载),只需使用:

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))
此外,您还需要在newpassword周围加引号:

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"
}

我收到以下错误-{“消息”:“发生了一个错误。”}所以你用随机生成的密码轰炸一个网站,想破坏别人的登录?希望此网站有验证码。不,出于安全原因,我正在尝试自动更新vault中的密码。我建议首先检查您回复的状态码。如果不是预期的(比如200),则打印response.reason。在这里,您将获得完整的错误消息