2

I want to pass json string from python code to shell script in original format like;

json_val = check_input_file['Item']['mappings']['S']
print(json_val) 

The output of above code is:

{
    "1": [
        "skipColumn"
    ],
    "2": [
        "firstname"
    ],
    "3": [
        "lastname"
    ],
    "4": [
        "email"
    ],
    "5": [
        "skipColumn"
    ],
    "6": [
        "ipaddress"
    ]
}

So now I am passing json_val to shell like:

init_script = '''#!/bin/bash 
       FOO="{0}"
       echo $FOO
        '''.format(json_val)

In FOO variable I get string without double quotes but I want it same as above.

I tried something like this

MAPPINGS=$(cat <<EOF
{"1":["skipColumn"],"2":["firstname"],"3":["lastname"],"4":["email"],"5":["skipColumn"],"6":["ipaddress"]}
EOF
)

But this is not what I want.

Am I missing something ?

oguz ismail
  • 1
  • 16
  • 47
  • 69
dar
  • 59
  • 1
  • 8

1 Answers1

2

You need to escape json_val for shell usage, otherwise double quotes will be dropped while the shell is performing quote removal.

It's also necessary to enclose $FOO in double quotes, otherwise you'd lose linebreaks in its content after the shell performed word splitting.

import shlex

init_script = '''
#!/bin/bash -
FOO={}
echo "$FOO"
'''.format(shlex.quote(json_val))

Online demo

oguz ismail
  • 1
  • 16
  • 47
  • 69
  • Probably also highlight the double quotes around the argument to `echo`. See also [When to wrap quotes around a shell variable?](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) – tripleee Jun 24 '20 at 14:29