1

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)
4
  • 1
    Use the json module to avoid problems. In fact, requests can do that for you. Don't try and format a json string yourself. Commented Mar 12, 2018 at 22:31
  • For the issue itself: escape the braces that aren't part of the formatting: """[\n {{\n "id"...\n }}\n]""". Commented Mar 12, 2018 at 22:32
  • can you give an example? Commented Mar 12, 2018 at 22:32
  • It's in the stdlib documentation for the json module, the requests documentation for how requests can take care of it by itself. Commented Mar 12, 2018 at 22:33

3 Answers 3

8

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

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

""".format(id="123", name="test")
Sign up to request clarification or add additional context in comments.

Comments

5
  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.

Comments

-1

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)

5 Comments

That's usable as a work-around, but doesn't solve the actual underlying issue.
@Evert: OP wrote in the question "I just need to format a multiline string" and I provided a way. I don't think the solution is incorrect and thus doesn't deserve the downvote!
@Evert: Sorry, I don't understand which values I didn't quote. I pasted the code after I was successfully able to run the code on my machine. (Obviously 8080 returned "Connection refused" but there is no syntax error.
Got it! nice catch

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.