Help us understand the problem. What is going on with this article?

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

More than 1 year has 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']

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

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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした