简体   繁体   中英

python string format keyError

I'm getting the following error while trying to execute my script

 ]""".format(id="123", name="test")
KeyError: '\n    "id"'

Here's my script. I just need to format a multiline string. I tried using a dictionary in the format section but that didn't work either.

import requests

payload = """[
  {
    "id":{id},
    "name": "{name}"
  }
]""".format(id="123", name="test")

headers = {"Content-Type": "application/json"}
r = requests.post("http://localhost:8080/employee", data=payload, 
headers=headers)
print(r.status_code, r.reason)
  1. You have opening and closing brackets. Format interprets them as a placeholder, you as a dict. Its content is, as the error says, \\n "id":{id}… and so on. If you do not mean { as a placeholder, double them.

  2. You are trying to write json yourself. Don't to that. Use the json module:

     json.dumps({"id": "123", name: "test"}) 

    Or even better: Let requests do that.

When using format , literal { 's and } 's need to be escaped by doubling them

payload = """[
  {{
    "id":{id},
    "name": "{name}"
  }}
]

""".format(id="123", name="test")

Try using %s instead of .format()

This works:

import requests

payload = """[
  {'id':%s,'name': %s
}
]"""%("123","test")

headers = {"Content-Type": "application/json"}
r = requests.post("http://localhost:8080/employee", data=payload,
headers=headers)
print(r.status_code, r.reason)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM