Search code examples
pythonjsonpayload

Pass string in JSON payload using python


I want to pass a randomly generated password to my payload. This is what I have-

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)

I'm not getting the desired output because it is not taking the new password string correctly. Please advise.


Solution

  • your payload is already a JSON string, so there's no need to call json.dumps(payload) , just use:

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

    calling json.dumps is needed when your payload is not a JSON string. for example:

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

    Also, you need to surround newpassword with quotes:

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

    In order to test it I changed your url to "https://httpbin.org/put" and it works fine. the output is:

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