Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
21
Help us understand the problem. What is going on with this article?
@kohbis

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

More than 3 years have passed since last update.

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']

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

21
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
kohbis
🍣

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
21
Help us understand the problem. What is going on with this article?