grinferno
grinferno

Reputation: 534

Escape double quotes when converting a dict to json in Python

I need to escape double quotes when converting a dict to json in Python, but I'm struggling to figure out how.

So if I have a dict like {'foo': 'bar'}, I'd like to convert it to json and escape the double quotes - so it looks something like:

'{\"foo\":\"bar\"}'

json.dumps doesn't do this, and I have tried something like:

json.dumps({'foo': 'bar'}).replace('"', '\\"') which ends up formatting like so:

'{\\"foo\\": \\"bar\\"}'

This seems like such a simple problem to solve but I'm really struggling with it.

Upvotes: 5

Views: 10943

Answers (2)

Ethan Rogers
Ethan Rogers

Reputation: 331

What you have does work. Python is showing you the literal representation of it. If you save it to a variable and print it shows you what you're looking for.

>>> a = json.dumps({'foo': 'bar'}).replace('"', '\\"')
>>> print a
{\"foo\": \"bar\"}
>>> a
'{\\"foo\\": \\"bar\\"}'

Upvotes: 0

nosklo
nosklo

Reputation: 222852

Your last attempt json.dumps({'foo': 'bar'}).replace('"', '\\"') is actually correct for what you think you want.

The reason you see this:

'{\\"foo\\": \\"bar\\"}'

Is because you're printing the representation of the string. The string itself will have only a single backslash for each quote. If you use print() on that result, you will see a single backslash

Upvotes: 9

Related Questions