Python用モジュール「json」でjsonファイルの特定のデータを取り出す方法についてソースコード付きでまとめました。
特定のデータ(要素)を取り出す
Pythonの標準モジュール「json」を用いて、JSON形式ファイルのロードします。
ロードしたデータは辞書型なので、キーを指定することで要素を取り出せます。
サンプルコード
サンプルプログラムのソースコードです。
# -*- coding:utf-8 -*-
import json
#JSON ファイルの読み込み
f = open('test.json', 'r', encoding="utf-8_sig")
json_data = json.load(f)
print(json_data["西住"]) # {'height': 158, 'position': '車長'}
print(json_data["秋山"]) # {'height': 157, 'position': '装填手'}
f.close()
test.json
読み込んだJSONファイルです。
{
"西住":{
"height": 158 ,
"position": "車長"
},
"秋山":{
"height": 157 ,
"position": "装填手"
}
}
– | 関連記事 |
---|---|
1 | ■【Python】jsonファイルの扱い方 ■【Python】Webスクレイピング入門 ■【Python】ネットワークプログラミング入門 |
2 | ■Python入門 基本文法 |
コメント