How to use str.format inside a string of json format? How to use str.format inside a string of json format? json json

How to use str.format inside a string of json format?


Format String Syntax section says:

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 }}.

So if you want to use .format method, you need to escape all JSON curly braces in your template string:

>>> '{{"fvAp": {{"attributes": {{"name": {}}}}}}}'.format('"app-name"')'{"fvAp": {"attributes": {"name": "app-name"}}}'

That looks really bad.

There's a better way to do that with string.Template:

>>> from string import Template>>> t = Template('{"fvAp": {"attributes": {"name": "${name}"}}')>>> t.substitute(name='StackOverflow')'{"fvAp": {"attributes": {"name": "StackOverflow"}}'

Though I suggest abandoning the idea of generating configs this way altogether and using a factory function and json.dumps instead:

>>> import json>>> def make_config(name):...     return {'fvAp': {'attributes': {'name': name}}}>>> app_config = make_config('StackOverflow')>>> json.dumps(app_config)'{"fvAp": {"attributes": {"name": "StackOverflow"}}}'