Search code examples
pythonpython-3.xstring

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?


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.