1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python JSONを扱う方法

Posted at

jsonとは

データをテキストで表すための形式
人間にもコンピューターにもわかりやすい

どんな時に使用するのか

webサービスやAPIでのデータのやり取りをする際

pythonでwebから天気情報を取得
➡データはjson形式で送られてくる

jsonのルール

・中身はキーと値のペア
・文字列は必ずダブルクォーテーションで囲む

import json

obj = {'item':'apple','price':120}
json_text = json.dumps(obj) # json形式の文字列が取得される
print(json_text)
print(type(json_text))

{"item": "apple", "price": 120}が取得される
※pythonではシングルクォートで記載しているが、
実際のJSONデータはダブルクォートで取得される

import json
obj = {'is_student': True,'license': None}
json_text = json.dumps(obj)
print(json_text)

{"is_student": true, "license": null}が取得される
※True → true、False → false、None → null など、PythonとJSONの書き方の違いがあります。

dump dumps load loads

dump=書き込む
load=読み込む
sがつくと文字列を表す

関数 使う場面 対象 説明
json.dump() Python → JSON ファイル 辞書などを直接ファイルに書き込む
json.dumps() Python → JSON 文字列 辞書などをJSON形式の文字列に変換
json.load() JSON → Python ファイル JSONファイルを読み込んで辞書に変換
json.loads() JSON → Python 文字列 JSON形式の文字列を辞書に変換
import json

# pythonの辞書型を作成➡このデータをjsonに変換して保存、読み書きをするため
data = {"name": "Keita", "age": 26}

# --- Python辞書 → JSON ---
# data.jsonという名前のファイルを書き込みモードで開く
# with構文はファイルを開いたあと、自動で閉じてくれるので便利

with open("data.json", "w") as f:
    json.dump(data, f) # dataをjson形式に変換し、ファイルfに書き込む

# dataをjson形式の文字列に変換し、代入
json_str = json.dumps(data)
print(json_str)  # {"name": "Keita", "age": 26}

# --- JSON → Python辞書 ---
# data.jsonを読み込みモードで開く
with open("data.json", "r") as f:
    data_from_file = json.load(f) # jsonファイルを読み込み、pythonの辞書型に変換

# 文字列から辞書型に変更
data_from_str = json.loads(json_str)
print(data_from_str["name"])  # Keita

なぜ文字列に変換する必要があるのか

pythonでJSON文字列に変換する理由
➡pythonの辞書はそのままでは外部に送る子ことができないから
pythonの辞書はpython専用のデータ構造
そこで文字列にすれば共通フォーマットになるという理由から

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?