0
0

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 1 year has passed since last update.

【Python】pathlibとjson.load関数を使って、JSONファイル内の値を取得する方法

Posted at

概要

  • Pythonでpathlibjson.loadを使って、JSONファイル内のキーとその値を取得する方法を記載します。

前提

  • Python 3.10.9

実行方法

  • Jsonファイルに以下のように記載します。
foo/hoge_key.json
{
    "name": "hoge",
    "gender": "male",
    "age" : "29"
}
  • 次に、pathlib関数を利用して以下のように記載します。
foo/views.py
from pathlib import Path
import json

key_path = Path('./foo/hoge_key.json')

with open(key_path, 'r') as f:
    key_json: Dict = json.load(f)

name = key_json.get('name')
gender = key_json.get('gender')
age = key_json.get('age')
  • 上記コードにより、以下が実施できます。
  1. pathlib.Pathクラスを使って、hoge_key.jsonのパスを表すkey_path変数を定義。
  2. open()関数を使ってファイルを開き、JSON データを読み込んでkey_json変数に格納。
  3. key_json変数からnamegenderageの値を取り出して、それぞれの変数に代入。
  4. 上記により、変数namegenderageを使うことで、JSONファイルで定義した値が使用できるようになりました。

json.load()とは?

  • JSON データを Python オブジェクトに変換するための関数。
  • JSON 形式の文字列またはファイルオブジェクトを引数に取り、それを Python の辞書やリストなどのオブジェクトに変換します。
  • 標準ライブラリのjsonモジュールを使用(import json)。
  • 参考:

パース (parse)とは?

例外処理について

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?