Python2.7: JSONを日本語で読み込む
まずはPython2.7でのJSONファイルの読み方です。
{ "lastUpdate": "20140218", "content":{ "title":"PythonでJson", "desc":"PythonでJsonを読み込みます" } }
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を使うのが少し危険かもという気がしてきました。 もし、他に文字列の良い置換と連結方法を見つけたら差し替えます。
- 作者: Mark Lutz,夏目大
- 出版社/メーカー: オライリージャパン
- 発売日: 2009/02/26
- メディア: 大型本
- 購入: 12人 クリック: 423回
- この商品を含むブログ (127件) を見る