πŸ› οΈToolsShed

XML ke JSON

Konversi dokumen XML ke format JSON secara instan.

Pertanyaan yang Sering Diajukan

Implementasi Kode

# 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.