LoginSignup
24
20

More than 5 years have passed since last update.

pythonでjsonファイルからの値取得

Last updated at Posted at 2018-03-12

pythonでjsonから値を取り出す。

たとえば、TwitterAPIで使うkeyたちをjsonファイルで管理したい。

こんな感じのjsonファイルを作成する。

config.json
{
    "api_key": {
        "CONSUMER_KEY": "xxxxxxxxxx",
        "CONSUMER_SECRET": "xxxxxxxxxx",
        "ACCESS_TOKEN": "xxxxxxxxxx",
        "ACCESS_TOKEN_SECRET":"xxxxxxxxxx"
    }
}

下記のようにすると、jsonから値を取り出せる。

app.py
# モジュールのインポート
import json

# ファイルを開く
json_file = open('config.json', 'r')
# JSONとして読み込む
json_obj  = json.load(json_file)

# 値の取り出し
CONSUMER_KEY        = json_obj['api_key']['CONSUMER_KEY']
CONSUMER_SECRET     = json_obj['api_key']['CONSUMER_SECRET']
ACCESS_TOKEN        = json_obj['api_key']['ACCESS_TOKEN']
ACCESS_TOKEN_SECRET = json_obj['api_key']['ACCESS_TOKEN_SECRET']

個人の趣味とかだと設定値系はついつい直書きしてしまうので、ちゃんと外だしするくせをつけたい。

24
20
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
24
20