python - String format a JSON string gives KeyError -


why code give 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"' 

you need double outer braces; otherwise python thinks { "file".. 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, producing json output, you'd better off using 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 lowercase true in output, required json standard.


Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -