python 字符串格式keyError

python string format keyError

我在尝试执行我的脚本时遇到以下错误

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

这是我的脚本。我只需要格式化一个多行字符串。我尝试在格式部分使用字典,但也没有用。

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)

尝试使用 %s 而不是 .format()

这个有效:

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)

当使用 format 时,文字 {} 需要 escaped by doubling them

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

""".format(id="123", name="test")
  1. 您有左括号和右括号。 Format 将它们解释为占位符,而您将其解释为字典。正如错误所说,它的内容是 \n "id":{id}… 等等。如果您不打算将 { 作为占位符,请将它们加倍。

  2. 您正在尝试自己编写 json。不要这样。使用 json 模块:

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

    或者更好:让请求做到这一点。