str.format() raises KeyError

Question:

The following code raises a KeyError exception:

addr_list_formatted = []
addr_list_idx = 0

for addr in addr_list: # addr_list is a list
    addr_list_idx = addr_list_idx + 1
    addr_list_formatted.append("""
        "{0}"
        {
        "gamedir"  "str"
        "address"  "{1}"
        }
    """.format(addr_list_idx, addr))

Why?

I am using Python 3.1.

Asked By: Dor

||

Answers:

The problem is that those { and } characters you have there don’t specify a key for formatting. You need to double them up, so change your code to:

addr_list_formatted.append("""
    "{0}"
    {{
    "gamedir"  "str"
    "address"  "{1}"
    }}
""".format(addr_list_idx, addr))
Answered By: Lasse V. Karlsen

Using str.format() to format JSON strings is not ideal because you would have to escape the curly braces, as the accepted answer notes.

While this method may be suitable for small JSON templates, it could make the template difficult to read if there are many curly braces that require escaping.

A better alternative could be string.Template:

from string import Template

addr_list = ["address 1, country 1", "address 2, country 2"]

addr_list_formatted = []
addr_list_idx = 0

template = Template("""
"${index}"
{
"gamedir"  "str"
"address"  "${address}"
}
""")

for addr in addr_list:
    addr_list_idx = addr_list_idx + 1
    formatted = template.substitute(index=addr_list_idx, address=addr)
    addr_list_formatted.append(formatted)
Answered By: Asa