skip to Main Content

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?

3

Answers


  1. Chosen as BEST ANSWER

    This is silly, but this worked.

    I don't exactly know how it worked internally but replacing

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

    with

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

    worked!

    I feel while accessing the variable os.environ["SHARED"] it was nullifying "" as the entire object had "" within itself and by adding ' this surrounded by object with " it was able to distinguish better.

    Just a theory!!!


  2. # 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"])
    
    Login or Signup to reply.
  3. 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))}'
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search