kade

技術系の記事を書いていきます。

Python2.7: JSONを日本語で読み込む

まずはPython2.7でのJSONファイルの読み方です。

{
    "lastUpdate": "20140218",
    "content":{
        "title":"PythonでJson",
        "desc":"PythonでJsonを読み込みます"
    }
}

上記date.jsonファイルを読み込むpython

import json

file = "date.json"
f = open(file)
data = json.load(f)
f.close()
last_date = json.dumps(data["lastUpdate"])
content_title = json.dumps(data["content"]["title"])
content_desc = json.dumps(data["content"]["desc"])

となります。 但し、これだと日本語がUnicode化しているので、 utf-8エンコードをします。

import json

file = "date.json"
f = open(file)
data = json.load(f)
f.close()
last_date = json.dumps(data["lastUpdate"])
last_date = eval("u'''%s'''" % last_date).encode('utf-8')
content_title = json.dumps(data["content"]["title"])
content_title = eval("u'''%s'''" % content_title).encode('utf-8')
content_desc = json.dumps(data["content"]["desc"])
content_desc = eval("u'''%s'''" % content_desc).encode('utf-8')

これでprintすれば正常に日本語が表示できます。

※追記 このevalを使うのが少し危険かもという気がしてきました。 もし、他に文字列の良い置換と連結方法を見つけたら差し替えます。

初めてのPython 第3版

初めてのPython 第3版