JSONファイルを読み込むときに使用するjson.loadを紹介します。
JSONファイルを読み込む
json.loadの書式は以下の通りです。
オブジェクト = json.load(ファイルオブジェクト [, エンコーディング])
json.loadは辞書オブジェクトを返します。
サンプル
以下のJSONファイル(sample.json)を読み込んでみます。
{
"ocean": {
"Squid":10,
"Octopus":8
},
"sky": {
"swallow":2,
"crow":2
}
}
open関数を使って読み込みモードでファイルを開きます。
# -*- coding: utf-8 -*-
import json
# ファイルを読み込みモードでオープン
with open('sample.json', 'r') as f:
# ファイルから読み込み
obj = json.load(f)
print obj # {u'sky': {u'crow': 2, u'swallow': 2}, u'ocean': {u'Squid': 10, u'Octopus': 8}}
print obj["ocean"] # {u'Squid': 10, u'Octopus': 8}
JSONを整えて表示する
JSONファイルきれいに表示したいときはjson.dumpsを利用します。
# -*- coding: utf-8 -*-
import json
# ファイルを読み込みモードでオープン
with open('sample.json', 'r') as f:
# ファイルから読み込み
obj = json.load(f)
print json.dumps(obj, sort_keys = True, indent = 2)
上のプログラムを実行すると元のJSONファイル(sample.json)と同じように整形されて表示されます。
よくあるエラー
以下のようなエラーが出る場合は、JSONファイルの書式が間違っている可能性があります。最後の要素に「,」が付いている間違いがよくあるので、注意してください。
ValueError: Expecting property name: line x column y (char z)