Wie verwende ich Python str.format in einer Zeichenfolge im json-Format?
Python Version 3.5
Ich versuche einen API-Aufruf durchzuführen, um ein Gerät mit json als Format zu konfigurieren. Einige der JSON-Werte variieren abhängig von der gewünschten Benennung. Daher muss eine Variable in der Zeichenfolge aufgerufen werden. Ich kann dies mit dem alten Stil erreichen%s... % (variable)
, aber nicht mit dem neuen Stil{}... .format(variable)
.
Failed EX:
(Testing with {"fvAp":{"attributes":{"name":(variable)}}})
a = "\"app-name\""
app_config = ''' { "fvAp": { "attributes": { "name": {} }, "children": [ { "fvAEPg": { "attributes": { "name": "app" }, "children": [ { "fvRsBd": { "attributes": { "tnFvBDName": "default" }, } } ] } }, { "fvAEPg": { "attributes": { "name": "db" }, "children": [ { "fvRsBd": { "attributes": { "tnFvBDName": "default" }, } } ] } } ] } } '''.format(a)
print(app_config)
Traceback (letzter Aufruf zuletzt): Datei "C: / ..., Zeile 49, in '' '.format (' a ') KeyError:' \ n" fvAp "'
Working EX:
a = "\"app-name\""
app_config = ''' { "fvAp": { "attributes": { "name": %s }, "children": [ { "fvAEPg": { "attributes": { "name": "app" }, "children": [ { "fvRsBd": { "attributes": { "tnFvBDName": "default" }, } } ] } }, { "fvAEPg": { "attributes": { "name": "db" }, "children": [ { "fvRsBd": { "attributes": { "tnFvBDName": "default" }, } } ] } } ] } } ''' % a
print(app_config)
Wie bekomme ich das zum Laufen mitstr.format
Methode