Home > database >  Json object export to environment variable in python returning string without ""
Json object export to environment variable in python returning string without ""

Time:01-10

I am creating a CDK stack using python. Here I am exporting json object in to a linux environment as it is a clodebuild step.

f"export SHARED=\"{json.dumps(shared)}\"" 

The only reason to use \" is i was getting an error for spaces with in the json object.

When I am trying to import environment object and load it as json i am getting json object without "".

{
    mts:{
        account_id:11111,
        workbench:aaaaa,
        prefix:rad600-ars-sil,rad600-srr-sil-stage1,rad600-srr-sil-stage2
    },
    tsf:{
        account_id:22222,
        workbench:bbbbb,
        prefix:yyyy

    }
}

with this object below loads is not working and giving out an error which states json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes

SHARED = json.loads(os.environ["SHARED"])

Am I missing something or is there a better way to send json object as environment variable?

CodePudding user response:

Using base64

One foolproof way is to encode your json string as base64 first.

import base64
json_bytestring = bytes(json.dumps(shared), 'utf-8')
b64_string = str(base64.b64encode(json_bytestring), 'utf-8')

command = f'export SHARED="{b64_string}"'
# ...

Then on the other end:

shared_b64 = os.environ['SHARED']
shared_bytestring = base64.b64decode(shared_b64)
SHARED = json.loads(str(shared_bytestring, 'utf-8'))

This technique also works for arbitrary binary data.

Using shlex.quote

Another way to do this would be to use shlex.quote to properly quote your json string for the shell command.

command = f'export SHARED={shlex.quote(json.dumps(shared))}'

CodePudding user response:

Dump the JSON object to a string, with ASCII encoding and double quotes for keys

shared_str = json.dumps(shared, ensure_ascii=True)

Set the environment variable

os.environ["SHARED"] = shared_str

Load the environment variable and parse it as JSON

SHARED = json.loads(os.environ["SHARED"])

  • Related