JSON解析编码导致unicode编码错误

JSON parsing encoding causes a unicode encode error

我需要在 bash 中解析一些简单的 JOSN,它包含没有外部依赖的非 ascii 字符,所以我使用了 python 解决方案 from this answer

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

这适用于 ascii 值,但其他值会引发此错误:

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

看着 this answer 我想我需要转换成 unicode 类型,但我不知道如何。

您已经有unicode,但是编码打印失败

那是因为您没有设置语言环境,将语言环境设置为 ASCII,或者您正在将 Python 结果传输到其他内容(但未将其包含在您的问题中)。在后一种情况下,Python 拒绝猜测连接到管道时使用的编解码器(否则它可以使用您的终端语言环境)。

PYTHONIOENCODING environment variable设置为合适的编解码器;例如,如果您的终端使用 UTF-8:

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