Metadata-Version: 2.4
Name: expatjson
Version: 0.1.0
Summary: XML を dict / JSON に変換するライブラリ / XML to dict and JSON converter based on Expat
Author: 孤独のコーヒー
License: MIT
Project-URL: Homepage, https://github.com/solitary-coffee/expatjson
Project-URL: Issues, https://github.com/solitary-coffee/expatjson/issues
Keywords: xml,json,expat,parser,converter
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: C++
Classifier: Topic :: Text Processing :: Markup :: XML
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: third_party/expat/COPYING
Dynamic: license-file

# expatjson

[![PyPI](https://img.shields.io/pypi/v/expatjson.svg)](https://pypi.org/project/expatjson/)
[![Python](https://img.shields.io/badge/python-3.9%20%7C%203.10%20%7C%203.11%20%7C%203.12%20%7C%203.13%20%7C%203.14-3776AB?logo=python&logoColor=white)](https://pypi.org/project/expatjson/#files)
[![OS](https://img.shields.io/badge/os-Windows%20%7C%20Linux%20%7C%20macOS-555555)](https://pypi.org/project/expatjson/#files)
[![Arch](https://img.shields.io/badge/arch-x86--64%20%7C%20ARM64-555555)](https://pypi.org/project/expatjson/#files)
[![Wheel](https://img.shields.io/pypi/wheel/expatjson.svg)](https://pypi.org/project/expatjson/#files)
[![CI](https://github.com/solitary-coffee/expatjson/actions/workflows/ci.yml/badge.svg)](https://github.com/solitary-coffee/expatjson/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/solitary-coffee/expatjson/blob/main/LICENSE)

XML を Python の `dict` や JSON に変換するライブラリです。パーサーには Expat を使っています。
追加の依存パッケージはありません。ビルド済みの wheel には C++ 拡張が含まれるため、コンパイラも不要です。

日本語 | [English](https://github.com/solitary-coffee/expatjson/blob/main/README.en.md)

```bash
pip install expatjson
```

## 目次

- [特長](#特長)
- [速度](#速度)
- [インストール](#インストール)
- [クイックスタート](#クイックスタート)
- [使い方](#使い方)
- [パーサーの指定](#パーサーの指定)
- [変換の規則](#変換の規則)
- [値になる場合とリストになる場合](#値になる場合とリストになる場合)
- [エラー処理](#エラー処理)
- [API リファレンス](#api-リファレンス)
- [開発](#開発)
- [お問い合わせ](#お問い合わせ)
- [ライセンス](#ライセンス)

## 特長

- C++ 拡張があれば自動で使います。ない環境では Python 実装が動きます。
- 標準ライブラリだけで動作します。
- DTD と実体宣言は受け付けません。入力サイズと階層にも上限があります。
- エラーには行番号、列番号、エラーコードが付きます。メッセージは日本語（既定）と英語に対応しています。
- 出力の形式は、属性が `@名前`、テキストが `#text`、繰り返しの要素がリストです。

## 速度

Windows 10、Python 3.11 で、生成した XML を変換した時間です（7 回の中央値）。値は文書の内容や環境によって
変わります。手元では `python bench/bench.py` で測れます。

| パーサー | 1.5 KiB | 149 KiB | 3 MiB |
|---|---:|---:|---:|
| **expatjson (native)** | **0.18 ms** | **11.2 ms** | **264 ms** |
| expatjson (Python) | 0.30 ms | 27.3 ms | 480 ms |
| xmltodict 1.0.4 | 0.57 ms | 53.2 ms | 1064 ms |

## インストール

```bash
pip install expatjson
```

Python 3.9 以降が必要です。次の環境には、C++ 拡張を含むビルド済みの wheel があります。

| OS | CPU | Python |
|---|---|---|
| Windows | x86-64、ARM64（3.11 以降） | 3.9〜3.14 |
| Linux（glibc・musl） | x86-64、ARM64 | 3.9〜3.14 |
| macOS | Intel、Apple シリコン | 3.9〜3.14 |

どちらのパーサーが使われるかは、次のコマンドで確認できます。

```bash
python -c "import expatjson; print(expatjson.backend())"   # native または python
```

<details>
<summary><code>python</code> と表示される場合（C++ 拡張をビルドする）</summary>

上の表にない環境では Python 実装が使われます。C++ 拡張を使うには、コンパイラを用意してから再インストールします。

| OS | コンパイラ |
|---|---|
| Windows | [Build Tools for Visual Studio](https://visualstudio.microsoft.com/ja/visual-cpp-build-tools/) の「C++ によるデスクトップ開発」 |
| Debian / Ubuntu | `sudo apt install build-essential python3-dev` |
| Fedora / RHEL | `sudo dnf install gcc-c++ python3-devel` |
| macOS | `xcode-select --install` |

```bash
EXPATJSON_REQUIRE_NATIVE=1 pip install --no-cache-dir --force-reinstall --no-binary expatjson expatjson
```

PowerShell の場合は、先に `$env:EXPATJSON_REQUIRE_NATIVE="1"` を実行してください。この環境変数を指定すると、
ビルドに失敗したときに Python 実装で代用せず、エラーで終了します。

</details>

<details>
<summary>PyPI を使わないインストール</summary>

```bash
# GitHub の最新版（コンパイラがない場合は Python 実装のみ）
pip install git+https://github.com/solitary-coffee/expatjson.git

# ダウンロードした wheel
pip install ./expatjson-<版>-<環境>.whl
```

</details>

## クイックスタート

```python
import expatjson

doc = expatjson.parse('<book id="1"><title>珈琲</title><tag>a</tag><tag>b</tag></book>')
print(doc)
# {'book': {'@id': '1', 'title': '珈琲', 'tag': ['a', 'b']}}

print(expatjson.to_json('<a><b>1</b></a>'))
# {"a":{"b":"1"}}
```

## 使い方

```python
# ファイル、gzip、Base64 でエンコードした gzip
doc = expatjson.parse_file("data.xml")
doc = expatjson.parse_gzip(payload)
doc = expatjson.parse_gzip_base64(text)

# 上限の変更（信頼できる入力に限る）
doc = expatjson.parse(xml, max_size=50 * 1024 * 1024, max_depth=500)

# 件数を気にせずループする
for tag in expatjson.as_list(expatjson.get_path(doc, "book", "tag")):
    print(tag)

# 整形した JSON を出力
print(expatjson.to_json(xml, indent=2))
```

コマンドラインからも実行できます。

```bash
expatjson data.xml --indent 2 -o data.json
cat data.xml | python -m expatjson -
```

## パーサーの指定

`backend` 引数で、使うパーサーを選べます。`to_json`、`parse_file`、`parse_gzip` でも指定できます。

| 値 | 動作 |
|---|---|
| `"auto"`（既定） | C++ 拡張があれば使い、なければ Python 実装を使う |
| `"native"` | 必ず C++ 拡張を使う。読み込めない場合は `BackendUnavailableError` |
| `"python"` | 必ず Python 実装を使う |

意図せず Python 実装で動くのを避けたいときは `"native"`、挙動を比べたいときや問題を切り分けたいときは
`"python"` を指定してください。

```python
doc = expatjson.parse("<a>1</a>", backend="python")

try:
    doc = expatjson.parse("<a>1</a>", backend="native")
except expatjson.BackendUnavailableError as error:
    print(error, error.hint())
```

```bash
expatjson data.xml --backend native              # C++ 拡張を使う
expatjson data.xml --backend python              # Python 実装を使う
EXPATJSON_BACKEND=python python your_app.py      # アプリ全体で C++ 拡張を読み込まない
```

## 変換の規則

| XML | 結果 |
|---|---|
| `<a/>` | `{"a": None}` |
| `<a>text</a>` | `{"a": "text"}` |
| `<a x="1"/>` | `{"a": {"@x": "1"}}` |
| `<a x="1">text</a>` | `{"a": {"@x": "1", "#text": "text"}}` |
| `<a><b>1</b></a>` | `{"a": {"b": "1"}}` |
| `<a><b>1</b><b>2</b></a>` | `{"a": {"b": ["1", "2"]}}` |

- 値はすべて文字列です。数値や真偽値には変換しません。
- テキストの前後の空白は削除します。コメントと処理命令は無視します。
- 名前空間の接頭辞は、そのままキーに含まれます。
- テキストと子要素の順序は保持されません。

## 値になる場合とリストになる場合

同じ親の中で、ある名前の要素が **1 つなら値、2 つ以上ならリスト**になります。同じ形式の XML でも、件数によって
結果の型が変わるので注意してください。

```python
one = expatjson.parse("<list><item>A</item></list>")
print(one)
# {'list': {'item': 'A'}}                       1 つの場合は文字列

two = expatjson.parse("<list><item>A</item><item>B</item></list>")
print(two)
# {'list': {'item': ['A', 'B']}}                2 つ以上はリスト

none = expatjson.parse("<list/>")
print(none)
# {'list': None}                                0 件の場合は item のキーがない
```

属性や子要素を持つ場合も同じです。

```python
print(expatjson.parse('<list><item id="1">A</item></list>'))
# {'list': {'item': {'@id': '1', '#text': 'A'}}}

print(expatjson.parse('<list><item id="1">A</item><item id="2">B</item></list>'))
# {'list': {'item': [{'@id': '1', '#text': 'A'}, {'@id': '2', '#text': 'B'}]}}
```

間に別の要素があっても、同じ名前の要素は出現順に 1 つのリストにまとまります。

```python
print(expatjson.parse("<r><a>1</a><b>x</b><a>2</a></r>"))
# {'r': {'a': ['1', '2'], 'b': 'x'}}
```

### 件数によらず同じコードで扱う

`as_list` を通すと、0 件でも 1 件でも常にリストになります。`get_path` は途中のキーがなくても `KeyError` を
送出しません。

```python
for xml in ("<list/>", "<list><item>A</item></list>", "<list><item>A</item><item>B</item></list>"):
    doc = expatjson.parse(xml)
    items = expatjson.as_list(expatjson.get_path(doc, "list", "item"))
    print(items)
# []
# ['A']
# ['A', 'B']
```

## エラー処理

解析に失敗すると、`ExpatJsonError`（`ValueError` のサブクラス）またはその派生クラスが送出されます。

### 例外の階層

```text
ValueError
└── ExpatJsonError
    ├── XMLSyntaxError
    │   └── EncodingError
    ├── SizeLimitError
    ├── DepthLimitError
    ├── ForbiddenXMLError
    ├── InputTypeError            (TypeError でもある)
    ├── CompressionError
    ├── FileReadError             (OSError でもある)
    └── BackendUnavailableError   (ImportError でもある)
```

引数の値が不正な場合（`backend="x"`、`max_depth=0`、`set_language("x")`）は、通常の `ValueError` です。

### 原因ごとの処理

`except` は、派生クラスから先に書いてください。

```python
def load(data):
    try:
        return expatjson.parse(data)
    except expatjson.EncodingError as error:
        print("文字コードのエラー:", error)
    except expatjson.XMLSyntaxError as error:
        print("構文エラー:", error.code, error.line, error.column)
    except (expatjson.SizeLimitError, expatjson.DepthLimitError) as error:
        print("上限超過:", error)
    except expatjson.ForbiddenXMLError as error:
        print("禁止されている宣言:", error)
    except expatjson.ExpatJsonError as error:
        print("その他のエラー:", error, error.hint())
    return None

load("<a><b></a>")
load("<!DOCTYPE a><a/>")
```

### エラーオブジェクトの内容

```python
try:
    expatjson.parse("<a>\n  <b></c>\n</a>")
except expatjson.ExpatJsonError as error:
    print(error)              # 開始タグと終了タグが対応していません（2 行目 8 文字目）
    print(error.hint())       # タグは、開いた順と逆の順に閉じてください。
    print(error.code)         # mismatched_tag
    print(error.line)         # 2
    print(error.column)       # 8
    print(error.byte_offset)  # 11
    print(error.snippet)      # エラー位置の前後の抜粋
    print(error.message("en"))
    print(error.to_dict())
```

| 属性・メソッド | 内容 |
|---|---|
| `code` | エラーの種類を表す文字列。条件分岐にはメッセージではなくこの値を使ってください |
| `line` / `column` | 行番号と列番号（1 始まり）。位置がない場合は `None` |
| `byte_offset` | 先頭からのバイト位置（0 始まり）。位置がない場合は `None` |
| `snippet` | エラー位置の前後（最大 60 バイト）。位置がない場合は `None` |
| `detail` | 補足情報（上限値、文字コード名、型名など） |
| `message(lang)` | 位置を含むエラーメッセージ（`"ja"` または `"en"`） |
| `hint(lang)` | 対処方法 |
| `to_dict(lang, include_snippet=False)` | ログや API レスポンス向けの `dict` |

### エラーコード一覧

| `code` | 例外 | 発生する例 | 対処 |
|---|---|---|---|
| `empty` | `XMLSyntaxError` | 空の文字列 | 入力が空でないか確認する |
| `unclosed` | `XMLSyntaxError` | `<a>`（閉じる前に終わる） | 最後まで読み込めているか確認する |
| `mismatched_tag` | `XMLSyntaxError` | `<a><b></a></b>` | 開いた順と逆の順に閉じる |
| `duplicate_attribute` | `XMLSyntaxError` | `<a x="1" x="2"/>` | 重複した属性を削除する |
| `undefined_entity` | `XMLSyntaxError` | `<a>&nbsp;</a>` | 定義済みの実体参照か数値文字参照を使う |
| `junk_after_document` | `XMLSyntaxError` | `<a/><b/>` | ルート要素を 1 つにする |
| `invalid_character` | `XMLSyntaxError` | 制御文字や NUL を含む | 該当の文字を取り除く |
| `misplaced_declaration` | `XMLSyntaxError` | `<?xml` の前に空白がある | 先頭の空白を削除する |
| `syntax` | `XMLSyntaxError` | 上記以外の構文の誤り | `<`、`&`、引用符を確認する |
| `encoding` | `EncodingError` | 存在しない文字コード名を宣言している | UTF-8 にするか、`str` に変換して渡す |
| `size` | `SizeLimitError` | `max_size` を超えている | 信頼できる入力なら上限を上げる |
| `depth` | `DepthLimitError` | 階層が `max_depth` を超えている | 信頼できる入力なら上限を上げる |
| `forbidden` | `ForbiddenXMLError` | `<!DOCTYPE …>` や実体宣言がある | DTD を削除する（許可する設定はありません） |
| `input_type` | `InputTypeError` | `parse(None)` | `str` かバイト列を渡す |
| `compression` | `CompressionError` | 壊れた gzip や Base64 | データを最後まで受信できているか確認する |
| `file` | `FileReadError` | 存在しないファイル | パスと権限を確認する |
| `backend` | `BackendUnavailableError` | C++ 拡張がない環境で `backend="native"` | 再インストールするか `"auto"` にする |

### ログへの出力

`str(error)` と `to_dict()` に XML の内容は含まれません。`snippet` には内容の一部が含まれるため、個人情報などを
扱う場合はログに出さないでください。

```python
import json
import logging

try:
    expatjson.parse("<a>")
except expatjson.ExpatJsonError as error:
    logging.warning(json.dumps(error.to_dict(), ensure_ascii=False))
```

### メッセージの言語

既定は日本語です。英語にするには、`expatjson.set_language("en")`、環境変数 `EXPATJSON_LANG=en`、
コマンドラインの `--lang en` のいずれかを指定します。

C++ 拡張と Python 実装では、使う Expat のバージョンが異なる場合があります。そのため、一部の不正な入力では
`code` や列番号が一致しないことがあります。

## API リファレンス

| 関数 | 説明 |
|---|---|
| `parse(xml, *, max_size, max_depth, backend="auto")` | `str` やバイト列を `dict` に変換 |
| `to_json(xml, *, indent=None, ensure_ascii=False, ...)` | JSON 文字列に変換 |
| `parse_file(path, ...)` | ファイルを読み込んで変換 |
| `parse_gzip(data, ...)` | gzip を展開して変換（展開後のサイズも `max_size` で制限） |
| `parse_gzip_base64(data, ...)` | Base64 をデコードして `parse_gzip` を実行 |
| `backend()` | 既定で使われるパーサー（`"native"` または `"python"`） |
| `as_list(value)` | リストに変換（`None` は空リスト） |
| `get_path(doc, *keys, default=None)` | キーをたどって値を取得 |
| `set_language("ja" / "en")` | エラーメッセージの言語を設定 |

`max_size`（既定 20 MiB）、`max_depth`（既定 200）、`backend` は、すべての変換関数で指定できます。

| 環境変数 | 効果 |
|---|---|
| `EXPATJSON_BACKEND=python` | C++ 拡張を読み込まない |
| `EXPATJSON_LANG=en` | エラーメッセージを英語にする |
| `EXPATJSON_PURE=1` | C++ 拡張をビルドしない |
| `EXPATJSON_REQUIRE_NATIVE=1` | C++ 拡張のビルドに失敗したらエラーにする |

## 開発

不具合の報告や要望は [Issues](https://github.com/solitary-coffee/expatjson/issues) にお願いします。

```bash
git clone https://github.com/solitary-coffee/expatjson.git
cd expatjson
pip install -e .
python -m unittest discover -s tests -v
```

変更内容は [CHANGELOG](https://github.com/solitary-coffee/expatjson/blob/main/CHANGELOG.md) を参照してください。

## お問い合わせ

[Issues](https://github.com/solitary-coffee/expatjson/issues) か <kikukazu.kk0226@gmail.com> までご連絡ください。
脆弱性の報告は [SECURITY](https://github.com/solitary-coffee/expatjson/blob/main/SECURITY.md) の方法でお願いします。

## ライセンス

[MIT License](https://github.com/solitary-coffee/expatjson/blob/main/LICENSE) © 孤独のコーヒー

[Expat](https://libexpat.github.io/)（MIT License、`third_party/expat/COPYING`）を同梱しています。
C++ 拡張には [pybind11](https://github.com/pybind/pybind11)（BSD-3-Clause）を使用しています。
