pyproject.toml(Python)からJSONへの変換

Pythonのpyproject.tomlをJSON形式に変換します。ビルドシステム設定、プロジェクトメタデータ、Black・Ruff・pytestのツール設定、依存関係の指定を解説します。

Real-World Configs

詳細な説明

pyproject.tomlはモダンPythonプロジェクトの標準設定ファイルで、PEP 518とPEP 621で定義されています。ビルドシステムの設定、プロジェクトメタデータ、ツール設定を1つのTOMLファイルに統合します。

典型的なpyproject.toml:

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "my-package"
version = "1.0.0"
description = "A sample Python package"
readme = "README.md"
requires-python = ">=3.9"
license = {text = "MIT"}
authors = [
  {name = "Alice", email = "alice@example.com"},
]
dependencies = [
  "requests>=2.28",
  "pydantic>=2.0",
]

[project.optional-dependencies]
dev = ["pytest>=7.0", "ruff>=0.1"]

[tool.ruff]
line-length = 88
target-version = "py39"

[tool.ruff.lint]
select = ["E", "F", "I"]

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-v --tb=short"

JSONに変換すると:

{
  "build-system": {
    "requires": ["hatchling"],
    "build-backend": "hatchling.build"
  },
  "project": {
    "name": "my-package",
    "version": "1.0.0",
    "description": "A sample Python package",
    "readme": "README.md",
    "requires-python": ">=3.9",
    "license": {"text": "MIT"},
    "authors": [
      {"name": "Alice", "email": "alice@example.com"}
    ],
    "dependencies": [
      "requests>=2.28",
      "pydantic>=2.0"
    ]
  },
  "project.optional-dependencies": {
    "dev": ["pytest>=7.0", "ruff>=0.1"]
  },
  "tool": {
    "ruff": {
      "line-length": 88,
      "target-version": "py39",
      "lint": {
        "select": ["E", "F", "I"]
      }
    },
    "pytest": {
      "ini_options": {
        "testpaths": ["tests"],
        "addopts": "-v --tb=short"
      }
    }
  }
}

変換時の注目ポイント:

  • [tool.*] セクションtool キーの下に深くネストされたJSONを作成します。各ツール(ruff、pytest、mypy)が独自の名前空間を持ちます。
  • 著者はインラインテーブルを使ったテーブル配列パターンを使用します。
  • オプション依存関係はグループ名をPEP 508要件文字列の配列にマッピングします。
  • ドット付きテーブルヘッダー[tool.ruff.lint])はネストされたJSONオブジェクトを生成します:tool -> ruff -> lint

JSON表現はPythonプロジェクト設定のプログラム的分析、依存関係解決ツール、メタデータを抽出する必要のあるCI/CDシステムに有用です。

ユースケース

複数パッケージからpyproject.tomlを読み取り、JSONに変換し、バージョン競合検出を含む統一された依存関係グラフを生成するPythonモノレポ管理ツールの構築。

試してみる — TOML ↔ JSON Converter

フルツールを開く