0

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'}?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.