Search code examples
pythonjsonstring-concatenation

Python string concatenation for JSON payload


I'm trying to modify this piece of code generated by Postman to replace hard-coded strings with string variables but I keep getting

KeyError: '\n\t"username"'

Here's the code

username = "jose"
email = "some_email"
password = "1234"

url = "some_url"

payload = '{\n\t\"username\": {},\n\t\"email\": {},\n\t\"password\": {}\n}'.format(username, email, password)
headers = {
  'Content-Type': 'application/json'
}

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

print(response.text.encode('utf8'))

Solution

  • You can properly form your json this way:

    import json
    username = "jose"
    email = "some_email"
    password = "1234"
    
    url = "some_url"
    
    payload = json.dumps({"username": username, "email":email, "password":password}, indent=4)
    headers = { 'Content-Type': 'application/json'}
    
    response = requests.request("POST", url, headers=headers, data=payload)
    
    print(response.text.encode('utf8'))