str.format fails with JSON?

Peter Otten __peter__ at web.de
Tue Feb 21 09:48:11 EST 2017


carlopires at gmail.com wrote:

> Hi,
> 
> When I run this piece of code:
> 
> 'From {"value": 1}, value={value}'.format(value=1)
> 
> Python complains about the missing "value" parameter (2.7.12 and 3.6.x):
> 
> Traceback (most recent call last):
>   File "test_format.py", line 1, in <module>
>     'From {"value": 1}, value={value}'.format(value=1)
> KeyError: '"value"
> 
> But according to the format string syntax
> (https://docs.python.org/2/library/string.html):
> 
> replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec]
> "}"
> field_name        ::=  arg_name ("." attribute_name | "[" element_index
> "]")*
> arg_name          ::=  [identifier | integer]
> attribute_name    ::=  identifier
> element_index     ::=  integer | index_string
> index_string      ::=  <any source character except "]"> +
> conversion        ::=  "r" | "s"
> format_spec       ::=  <described in the next section>
> 
> The replacement_field, which in this case, is composed by an identifier,
> shouldn't have quotation marks. Here is the lexical definition for an
> identifier (according to the documentation):
> 
> identifier ::=  (letter|"_") (letter | digit | "_")*
> letter     ::=  lowercase | uppercase
> lowercase  ::=  "a"..."z"
> uppercase  ::=  "A"..."Z"
> digit      ::=  "0"..."9"
> 
> So according to the specification, {value} should be recognized as a valid
> format string identifier and {"value"} should be ignored.

I'd rather say '{"value"}' unspecified as "value" isn't a proper field_name 
and literal {} have to be escaped.
> 
> Python seems to not follow the specification in the documentation.
> Anything inside the keys is accepted as identifier.

It does not enforce that you follow the specification, but if you do and 
properly escape the braces by doubling them you get the correct result

>>> 'From {{"value": 1}}, value={value}'.format(value=1)
'From {"value": 1}, value=1'





More information about the Python-list mailing list