Python string concatenation for JSON payload

M. Elauzei

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'))
Seyi Daniel

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'))

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related