Skip to content

Instantly share code, notes, and snippets.

@dogrunjp
Last active September 2, 2020 02:31
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dogrunjp/161b06de2d56e4db7a74 to your computer and use it in GitHub Desktop.
Save dogrunjp/161b06de2d56e4db7a74 to your computer and use it in GitHub Desktop.
Pythonのjson.load() で文字列の値をunicodeにcastしないで扱いたいとき…

Python のjson.load()で文字列の値をunicodeにcastしないで扱いたいとき。

たとえば JSONからid だけ読み込んで 内部的に生成されたasciiなstringと差分のリストを取得したいとかを想定しているのですが、 json.load()でunicodeに変換されないようにしたい!というだけなのに意外にちょっとした手間がかかるのでメモしておきます。


with open(file_path, 'r') as f:
            jsonData = json.load(f)
            

このように普通にjson.load()するとPython2.xの場合?文字列はunicodeにキャストされ、u'xx'のようになります。

文字列をそのまま取得したい場合はobject_hookオプションを使います。

def ascii_encode_dict(data):
    ascii_encode = lambda x: x.encode('ascii') if isinstance(x, unicode) else x
    return dict(map(ascii_encode, pair) for pair in data.items())

with open(file_path, 'r') as f:
    jsonData = json.load(f, object_hook=ascii_encode_dict)

追記

strを要素としたリストとunicodeを要素としたリストを set()にキャストして差分を取ると、asciiで表現できる文字についてはしっかり差分要素がstrで返ります。

したがって、今回差分リストを取得するという目的の自分の用途にとってはあまり意味が無かった、、ことになりました。


参考(というかそのまま)

How to get string Objects instead of Unicode ones from JSON in Python?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment