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

How to escape backslash loads from dotenv json variable python

I have a dotenv variable saved into .env file (in json format).
Example:

my_env_variable = '{"ip": "xx.xx.xxx.xxx",
    "user": "my\user",
    "password": "password"}'    

Reading this variable form my .py script (connection is a enum type DBConnection)

from os import environ as env
from dotenv import load_dotenv
load_dotenv()

class DatabaseUtils:
   @staticmethod
   def get_data_from_db(connection:DBConnection , script_path, query):
      selected_connection = json.loads(env[connection.value].replace('\n', ''))

      user = selected_connection["user"]

Unfortunately, I got an error message, due to backslash in user (coming from json) and gives error:

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

self = <json.decoder.JSONDecoder object at 0x000001295223F0D0>
s = '{"instance_ip": "xx.xx.xxx.xxx",        "user": "my\user",        "password": "password"'
idx = 0

json.decoder.JSONDecodeError: Invalid \escape: line 1 column 70 (char 69)

What is the best solution to escape the backslash? Unfortunately, I cannot omit like r’value’ because the parameter is in the .env file and cannot add "r" before the json

Edit: I also try with json.dumps before json.loads, but in this case I cannot

selected_connection["user"]

anymore, because selection_connection became a str

>Solution :

Backslashes needs to be escaped once for env file and once for JSON string, so two times:

my_env_variable = '{"ip": "xx.xx.xxx.xxx",
    "user": "my\\\\user",
    "password": "password"}'
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