I was trying to format a small JSON for some purposes, like this: '{"all": false, "selected": "{}"}'.format(data) to get something like {"all": false, "selected": "1,2"}
It's pretty common that the "escaping braces" issue comes up when dealing with JSON.
Try doing this:
Python 3.6+ (2017)
In the recent versions of Python one would use f-strings (see also PEP498).
With f-strings one should use double
{{
or}}
produces the desired
If you need to resolve an expression in the brackets instead of using literal text you'll need three sets of brackets:
produces
Although not any better, just for the reference, you can also do this:
It can be useful for example when someone wants to print
{argument}
. It is maybe more readable than'{{{}}}'.format('argument')
Note that you omit argument positions (e.g.
{}
instead of{0}
) after Python 2.7Reason is ,
{}
is the syntax of.format()
so in your case.format()
doesn't recognize{Hello}
so it threw an error.you can override it by using double curly braces {{}},
or
try
%s
for text formatting,You escape it by doubling the braces.
Eg:
The OP wrote this comment:
It's pretty common that the "escaping braces" issue comes up when dealing with JSON.
I suggest doing this:
It's cleaner than the alternative, which is:
Using the
json
library is definitely preferable when the JSON string gets more complicated than the example.