How to expand environment variable in python while escaping special characters?
<p>On the host, I have an environment variable with a quote sign in the value, something like:</p>

<pre><code>export VALUE_WITH_QUOTE_FROM_OS='quote"value'
</code></pre>

<p>and when I echo on bash, it's fine</p>

<pre><code>#echo $VALUE_WITH_QUOTE_FROM_OS
quote"value
</code></pre>

<p>I have a following json string:</p>

<pre><code>json_str = '{"key":"${VALUE_WITH_QUOTE_FROM_OS}"}'
</code></pre>

<p>Then I want to expand the environment variable inside a python script before further processing, something like this</p>

<pre><code>json_str = os.path.expandvars(json_str)
json_dict = json.loads(json_str)
</code></pre>

<p>However, this expansion would break the json syntax, since the json_str had become </p>

<pre><code>'{"key":"quote"value"}' (&lt;== bad unescaped quote in the value)
</code></pre>

<p>instead of </p>

<pre><code>'{"key":"quote\"value"}' 
</code></pre>

<p>Is there anyway I can inform os.path.expandvars() to escape the double quote when expanding the value? If not, how should I expand the environment variable so that the double quote can be escaped.</p>

<p><strong>Note 1</strong> The value of the environment variable is a security token, so I have to keep the double quote there as it is.</p>

<p><strong>Note 2</strong> Current json interface has already been determined and used extensiely as it is. This json_str is passed to me, therefore I should and must only expand the environment variable denoted by ${} in the json string, no other modification are allowed.</p>

<p><strong>Note 3</strong> This json_str is extremely large with complex, dynamic, nested structure and is consumed by multiple clients who cannot access host os environment variable. Although it's possible for me to load the json_str first, traverse the dictionary to resolve the environment variable, and then dump the dict back to json_str and then dispatch to all the clients, I think it is less efficient compared to processing it just as a string.</p>

<p>Thanks.</p>