Search code examples
pythonjsondotenv

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:

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