13
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jsonファイルの読み込みまとめ

Posted at

最近,JSON形式のファイルを使い始めたので,そのまとめです.

Python3による読み込み

Python3での読み込み方法として,**「jsonを使った読み込み」**をとりあげます.
その他,pandasなどでも読み込めるのでそれは他を参照して下さい.
この方法には,json.loadjson.loadsが存在します.
json.load : JSONファイルを辞書として読み込むときに使います.
json.loads : JSON形式で書かれた文字列を読み込みます.
今回は,外部ファイルからの読み込みなので json.loadを使います.

json.loadによる読み込み

JSONファイルを辞書として読み込むには,これを使います.
以下,具体的な書き方です.

json_load.py
import json
with open('test.json') as f:
    data = json.load(f)

とこうするだけ.簡単ですね.
しかし,windowsユーザーは注意.windowsのデフォルトでの読み込みで次のエラーが発生します.
UnicodeDecodeError: 'cp932' codec can't decode byte 0x86
そのため,ちゃんと文字コードを指定しましょう.

json_load.py
import json
with open('test.json', encoding='utf-8') as f:
    data = json.load(f)

JavaScriptでの読み込み

JavaScriptでの読み込み方法としてjQueryでの読み込みを取り上げます.

test.js
$.getJSON("test.json", function (data) {
    //読み込んだdataに対する処理
});
13
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?