String format a json String gives KeyError

Why does this code give a KeyError?

output_format = '{ "File": "{filename}", "Success": {success}, "ErrorMessage": "{error_msg}", "LogIdentifier": "{log_identifier}" }'

print output_format.format(filename='My_file_name',
                           success=True,
                           error_msg='',
                           log_identifier='123')

Error message

KeyError: ' "File"'

Answers


You need to double the outer braces; otherwise Python thinks { "File".. is a reference too:

output_format = '{{ "File": "{filename}", "Success": {success}, "ErrorMessage": "{error_msg}", "LogIdentifier": "{log_identifier}" }}'

Result:

>>> print output_format.format(filename='My_file_name',
...                            success=True,
...                            error_msg='',
...                            log_identifier='123')
{ "File": "My_file_name", "Success": True, "ErrorMessage": "", "LogIdentifier": "123" }

If, indicentally, you are producing JSON output, you'd be better off using the json module:

>>> import json
>>> print json.dumps(dict(File='My_file_name',
...                            Success=True,
...                            ErrorMessage='',
...                            LogIdentifier='123'))
{"LogIdentifier": "123", "ErrorMessage": "", "Success": true, "File": "My_file_name"}

Note the lowercase true in the output, as required by the JSON standard.


Need Your Help

How do I add parameters on Modelio, UML

uml modelio

I can't really find how to add arguments on a Operation, how can I do it? The picture above is the program I use, Modelio... How do I add arguments on Operation? And how do I add a return value?

Performance of calling delegates vs methods

c# .net performance delegates

Following this question - http://stackoverflow.com/questions/2082615/pass-method-as-parameter-using-c and some of my personal experience I'd like to know a little more about the performance of call...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.