-1

In python, I'm trying to create a string by format()

json_data_resp = '{"error":false,"code":"{0}","mac":"{1}","message":"Device configured successfully"}'.format(activation_code, macaddress)

When I execute this code, it gives me an error like so:

KeyError: '"error"'

What is it that I'm doing incorrectly?

Ouroboros
  • 1,432
  • 1
  • 19
  • 41

4 Answers4

3

You should escape literal braces by doubling them:

json_data_resp = '{{"error":false,"code":"{0}","mac":"{1}","message":"Device configured successfully"}}'.format(activation_code, macaddress)

Excerpt from Format String Syntax:

Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

blhsing
  • 91,368
  • 6
  • 71
  • 106
  • 1
    Since I'm using micropython, the format is what is recommended instead of concatenation. This is exactly what I was unable to catch. Thanks – Ouroboros Aug 10 '18 at 04:03
0

You can do '%' for string formatting:

json_data_resp = '{"error":false,"code":"%s","mac":"%s","message":"Device configured successfully"}'%(activation_code, macaddress)
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

It is trying to insert a variable inside of the curly braces you put around the entire string. If you want to have curly braces in a formatted string, you have to use two.

string = "{{test_number: {0}}}".format(37)
Aeolus
  • 996
  • 1
  • 8
  • 22
0

Format strings have fields inside curly braces. Each field has an optional number, name, or expression, and optional :spec, and an optional !conversion.

So, when you use this as a format string:

'{"error":false,"code":"{0}","mac":"{1}","message":"Device configured successfully"}'

You have a field named "error", with spec false,"code":"{0}","mac":"{1}","message":"Device configured successfully".

To format that field, you need a keyword parameter named "error", and of course you don't have one.


Obviously, you didn't want that whole thing to be a field. But that means you need to escape the braces by doubling them:

'{{"error": false,"code":"{0}","mac":"{1}","message":"Device configured successfully"}}'

Or, better… why are you trying to create a JSON string by str.format in the first place? Why not just create a dict and serialize it?

json_data_resp = json.dumps({
    "error": False, "code": activation_code, "mac": macaddress,
    "message": "Device configured successfully"})
abarnert
  • 354,177
  • 51
  • 601
  • 671