I have a dictionary in Python that I would like to serialize in JSON and convert to a proper C string so that it contains a valid JSON string that corresponds to my input dictionary. I'm using the result to autogenerate a line in a C source file. Got it? Here's an example:
>>> import json
>>> mydict = {'a':1, 'b': 'a string with "quotes" and \t and \\backslashes'}
>>> json.dumps(mydict)
'{"a": 1, "b": "a string with \\"quotes\\" and \\t and \\\\backslashes"}'
>>> print(json.dumps(mydict))
{"a": 1, "b": "a string with \"quotes\" and \t and \\backslashes"}
What I need to generate is the following C string:
"{\"a\": 1, \"b\": \"a string with \\\"quotes\\\" and \\t and \\\\backslashes\"}"
In other words, I need to escape the backslash and double-quote on the result of calling json.dumps(mydict). At least I think I do.... Will the following work? Or am I missing an obvious corner case?
>>> s = '"'+json.dumps(mydict).replace('\\','\\\\').replace('"','\\"')+'"'
>>> print s
"{\"a\": 1, \"b\": \"a string with \\\"quotes\\\" and \\t and \\\\backslashes\"}"