XML → JSON 変換
XMLドキュメントをJSON形式に即座に変換します。
よくある質問
コード実装
# pip install xmltodict
import xmltodict
import json
xml = """<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book genre="fiction" id="1">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<price>12.99</price>
</book>
<book genre="sci-fi" id="2">
<title>Dune</title>
<author>Frank Herbert</author>
<price>14.99</price>
</book>
</bookstore>"""
# Parse XML to ordered dict, then to JSON
data = xmltodict.parse(xml)
result = json.dumps(data, indent=2, ensure_ascii=False)
print(result)
# {
# "bookstore": {
# "book": [
# { "@genre": "fiction", "@id": "1", "title": "The Great Gatsby", ... },
# { "@genre": "sci-fi", "@id": "2", "title": "Dune", ... }
# ]
# }
# }
# Force single child as list
data = xmltodict.parse(xml, force_list={"book"})Comments & Feedback
Comments are powered by Giscus. Sign in with GitHub to leave a comment.