Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot convert string variable to raw

I have seen few examples on how to convert string variable to raw one using interpolation, but it doesn’t work for me:

import json


j = '{"value": "{\"foo\": \"bar\"}"}'

print(j)
print(fr"{j}")
print(r'{"value": "{\"foo\": \"bar\"}"}') # Works
print(json.loads(r'{"value": "{\"foo\": \"bar\"}"}'))
try:
    print(json.loads(fr"{j}"))  # Doesn't work
except Exception as e:
    print(e)

What am I doing wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

j = '{"value": "{\\"foo\\": \\"bar\\"}"}'

print(json.loads(j))

In order for it to be valid JSON, the \ has to present to escape the quotes. So, you’d need to escape the backslashes in the original string.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading