1

I have a json file and would like to put it in the enviroment variable, however, every time that I run my code I get an error.

Since I want to keep the credentials in the enviroment variable, I put it in an .env file. Now, what I need is to use this credential stored in the enviroment variable in the code.

It is stored like this: creds= '{ "type": "somethinghere", "project_id": "somethinghere", "private_key_id": "somethinghere", "private_key": "somethinghere" }'

The code I am running contains an script to write to google sheets:

load_dotenv()


API_Key = os.getenv("API_Key")
creds = os.getenv("creds")
json_creds = json.loads(creds)
class DataWriter:

def __init__(self, filename: str, sheetname: str) -> None:
    self.filename = filename
    self.sheetname = sheetname
    self.scopes = [
        'https://www.googleapis.com/auth/spreadsheets',
        'https://www.googleapis.com/auth/drive'
    ]

    self.credentials = ServiceAccountCredentials.from_json_keyfile_name(
        json_creds, self.scopes)
    # access the json key you downloaded earlier
    # authenticate the JSON key with gspread

def write(self, data) -> None:
    file = gspread.authorize(self.credentials)
    sheet = file.open(self.filename).worksheet(self.sheetname)
    return set_with_dataframe(sheet, data, include_index=False,
                              include_column_header=True, resize=False)

I am getting the following error: JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Would you be able to assist? The reason I want to do it is because I need to use Github actions. I am open to the best practice.

Thanks

  • In your question, you say you are trying to store json in an environment variable, but in the example you give, you're reading an environment variable and then parsing it as json. – Carson Mar 14 '22 at 18:42
  • If you have a json file, and you're trying to make the example work, I believe you should just put the filename into the ` self.credentials = ServiceAccountCredentials.from_json_keyfile_name(` method. Could you please update your post to clarify where the data is and where you need it to be? – Carson Mar 14 '22 at 18:43
  • Thanks. I have updated the comments. I hope it is more clear what is my goal. – Caroline Silva Mar 14 '22 at 18:52
  • Thank you, that makes it a lot more clear. There are two things I think you should be aware of: 1.) Are you sure that `creds` is loading a value? My first guess is that the enviroment variable isn't set for whatever reason. You can just add `print(creds)` after the line you load it. (Also, the `env` command in your terminal shows you your full enviroment) 2.) I think the method you're using is expecting a json filename, not a decoded json object. Have you confirmed in the docs what the expected arguement is? – Carson Mar 14 '22 at 19:00

0 Answers0