Home > Back-end >  json.dumps() : how to escape double quotes with a single backslash
json.dumps() : how to escape double quotes with a single backslash

Time:08-24

when I use json.dumps(), I get the following output:

>>> json.dumps("abc")
'"abc"'

This results in unescaped double quotes. Is there a way to always have one backslash, something like:

>>> json.dumps("abc", additional_param=?)
'\"abc\"'

CodePudding user response:

Not sure if this is exactly what you want, but it might be:

import json

print(json.dumps("abc").replace(r'\"', '"').replace('"', r'\"'))

Result:

\"abc\"

CodePudding user response:

It sounds like what you're asking for is double-encoded JSON.

print(json.dumps(json.dumps("abc")))

...results in:

"\"abc\""

By contrast, single-encoding (without the REPL's implicit repr()) looks like:

print(json.dumps("abc"))

...and emits the correctly-encoded JSON document:

"abc"

Note that this is correct JSON exactly as it is; no backslashes are needed.

  • Related