str.format fails with JSON?
Chris Angelico
rosuav at gmail.com
Tue Feb 21 09:38:54 EST 2017
On Wed, Feb 22, 2017 at 1:23 AM, <carlopires at gmail.com> wrote:
> Hi,
>
> When I run this piece of code:
>
> 'From {"value": 1}, value={value}'.format(value=1)
Firstly, this code is in error; I suspect you wanted a couple of
literal braces, so what you want is:
>>> 'From {{"value": 1}}, value={value}'.format(value=1)
'From {"value": 1}, value=1'
So everything from here on is about exactly *what* error gets raised.
> 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):
>
> The replacement_field, which in this case, is composed by an identifier, shouldn't have quotation marks.
>
> So according to the specification, {value} should be recognized as a valid format string identifier and {"value"} should be ignored.
>
> Python seems to not follow the specification in the documentation. Anything inside the keys is accepted as identifier.
I agree. It'd be beneficial to add that kind of a check, as a means of
detecting cases where someone forgot to double a brace. Something
like:
InvalidKeyError: '"value"' - did you intend to use {{ }} ?
Not sure how hard the check would be to write, but it'd help to
highlight a particular class of bug.
ChrisA
.
More information about the Python-list
mailing list