JSON parsing encoding causes a unicode encode error
<p>I need to parse some simple JOSN in bash which contains non-ascii characters without external dependencies, so I used a python solution <a href="http://stackoverflow.com/a/1955555/296446">from this answer</a></p>

<pre><code>cat $JSON_FILE  | python -c "import sys, json; print json.load(sys.stdin)['$KEY']"
</code></pre>

<p>This works for ascii values but other values throws this error:</p>

<blockquote>
  <p>'ascii' codec can't encode character u'\u2019' in position 1212: ordinal not in range(128)</p>
</blockquote>

<p>Looking at <a href="http://stackoverflow.com/a/8591554/296446">this answer</a> I think I need to cast to the <code>unicode</code> type, but I don't know how.</p>

<p>You already have <code>unicode</code>, but <strong>encoding</strong> when printing fails.</p>

<p>That's either because you don't have a locale set, have your locale set to ASCII, or you are piping the Python result to something else (but did not include that in your question).  In the latter case Python refuses to guess what codec to use when connected to a pipe (it can use your terminal locale otherwise).</p>

<p>Set the <a href="https://docs.python.org/2/using/cmdline.html#envvar-PYTHONIOENCODING" rel="nofollow"><code>PYTHONIOENCODING</code> environment variable</a> to a suitable codec; if your terminal uses UTF-8 for example:</p>

<pre><code>cat $JSON_FILE  | PYTHONIOENCODING=UTF-8 python -c "import sys, json; print json.load(sys.stdin)['$KEY']"
</code></pre>

python json bash python-2.x