Reputation: 338
Here is the problem:
json.loads('{"reg": "\\\\d"}')
yeilds {'reg': '\\d'}
but:
json.dumps({'reg': '\d'})
yeilds '{"reg": "\\\\d"}'
My question is which input string in json.loads()
can I get {'reg': '\d'}
?
Upvotes: 0
Views: 185
Reputation: 209
The two values {'reg': '\\d'}
and {'reg': '\d'}
are actually the same thing. The Python REPL print stage will automatically replace special characters with there escaped equivalent, meaning that a single stored \
will get printed as \\
. Also, since \d
isn't a valid string escape sequence, it gets automatically replaced with \\d
when the string is parsed.
A recommendation that I have for working with Python regular expression strings is to prefix the string with r
, meaning that the \
character will be treated as a literal for everything except for escaping a quote. For example, using r'\d'
will guarantee that the Python string parser will never interpret \d
as an escape sequence before the Python regular expression parser gets to it. JSON doesn't support raw strings, so you will still have to escape any backslashes found in that file if you are manually editing it.
Upvotes: 2