XML to JSON Converter
XMLをJSONへ、JSONをXMLへブラウザ内で相互変換。属性・配列化ルールをカスタマイズできます。
How to Use the XML to JSON Converter
This free online converter turns XML documents into JSON, entirely in your browser. Paste your XML, adjust the attribute prefix and text-node key if needed, and click Convert. The tool parses the input with the native DOMParser, so the validation behavior matches what Chrome, Firefox, and Edge actually do. If the XML is malformed, the parser error — including the line and column reported by the browser — is shown instead of a silent wrong result. A reverse mode converts JSON back to XML with proper escaping of &, <, and quotes.
Features
- XML to JSON and JSON to XML in one tool, with a single direction toggle
- Configurable attribute prefix (default
@) and text-node key (default#text) - Repeated sibling elements are collapsed into JSON arrays automatically
- Parse errors are surfaced with the line and column reported by the browser engine
- 100% client-side: no upload, no server, no data retention
Conversion Rules
- Sibling elements that share a tag name become a JSON array
- Attributes become keys prefixed with
@(e.g.id="1"→"@id": "1") - An element containing only text becomes a plain string value; an empty element becomes
"" - When an element has both attributes (or children) and text, the text goes under
#text - All values are kept as strings — the tool never guesses whether
007should become a number
What is XML to JSON conversion used for?
XML is still everywhere: SOAP APIs, RSS and Atom feeds, sitemaps, Maven and Android configuration, and decades of enterprise system exports. Modern frontends and data pipelines, however, speak JSON. Converting XML to JSON lets you inspect a legacy API response as a JavaScript object, feed feed-reader data into a JSON-based tool chain, or compare two structures with a JSON diff. Because XML attributes and mixed content have no direct JSON equivalent, every converter must pick a mapping convention — this tool uses the same @/#textconvention as Python's popular xmltodict library, so the output is directly usable in existing scripts.
XML to JSON Converterの使い方
変換したいXMLを入力欄に貼り付けて「変換」を押すだけで、JSONが即座に表示されます。パースにはブラウザ標準のDOMParser(application/xml)を使用しており、整形式でないXMLはparsererror として行・列番号付きのエラーが表示されます。変換ルールは次の3点が基本です: (1) 同名の兄弟要素は配列に、(2) 属性は @ プレフィックス付きキーに、(3) テキストだけを持つ要素は文字列値になります。属性プレフィックスとテキストキーはオプションで変更でき、 逆方向(JSON → XML)の変換にも対応しています。
実務での活用例
1. SOAP・レガシーAPIレスポンスの解析
社内の基幹システムや決済ゲートウェイがSOAP/XMLを返す場合、レスポンスを本ツールでJSON化すると、 ネスト構造をJavaScriptオブジェクトとして読めるようになります。変換後はJSON Formatterでの整形や、JSONベースの差分比較がそのまま使えます。 認証トークンを含むレスポンスでも、ブラウザ内処理のため外部に漏れません。
2. RSS・サイトマップの中身を確認する
RSSフィードや sitemap.xml は同名要素(item や url)の繰り返しが本体です。 本ツールに貼り付けると、これらが自動的にJSON配列へ集約されるため、件数の確認や特定エントリの抽出が容易になります。 要素が1件しかないフィードでは配列にならない点(変換ルール参照)にだけ注意してください。
3. XML設定ファイルのJSON移行
ビルドツールやCI設定をXMLからJSON/YAMLベースへ移行する際の下書きとして使えます。まず本ツールでJSON化し、JSON / YAML ConverterでYAMLへ変換すれば、手作業の書き写しによる 転記ミスを減らせます。属性中心のXMLでは @ キーが残るため、最終形に合わせてキー名を整理してください。
よくあるエラーと対処 / Common Errors and Fixes
DOMParser が報告する parsererror の代表的なメッセージと、JSON → XML 変換時のエラーをまとめました。
Typical parsererror messages reported by DOMParser, plus errors in the JSON-to-XML direction.
| エラー / Error | 原因 / Cause | 対処 / Fix |
|---|---|---|
Opening and ending tag mismatch | 開始タグと終了タグの不一致 Start and end tags do not match | タグ名の対応とネスト順を修正。XML Formatterで整形すると見つけやすい Fix the tag pairing and nesting order; formatting the XML first helps |
xmlParseEntityRef: no name / EntityRef: expecting ';' | エスケープされていない生の &A raw unescaped & in text or attributes | & に置換するか、テキストをCDATAで囲むReplace with & or wrap the text in CDATA |
Extra content at the end of the document | ルート要素が2つ以上ある More than one root element | 全体を単一のルート要素で包む。XMLはルート1つが必須 Wrap everything in a single root element — XML requires exactly one |
Start tag expected, '<' not found / Document is empty | XML宣言の前に余計な文字・BOM・空入力 Leading text or BOM before the declaration, or empty input | 先頭の余分な文字を削除し、<?xml または開始タグから始めるRemove leading characters so input starts at <?xml or the first tag |
attributes construct error | 属性値の引用符漏れ・閉じ忘れ Attribute value missing or unclosed quotes | すべての属性値を "..." で囲む。値内の引用符は " にQuote every attribute value; escape inner quotes as " |
JSON構文エラー: Unexpected token ...(JSON → XML時) | 入力JSONの構文エラー(末尾カンマ・シングルクォート等) Invalid JSON input (trailing comma, single quotes, etc.) | JSON Formatterで先に検証してから変換する Validate the JSON with the JSON Formatter first |
出力に @xmlns キーが現れる | 名前空間宣言も通常の属性として変換される Namespace declarations are converted like ordinary attributes | 仕様どおりの動作。不要ならJSON側で @xmlns キーを削除するExpected behavior; delete the @xmlns keys afterwards if unwanted |
言語別コード例 / Code Examples by Language
同じ変換をアプリケーション側で再現するための最小サンプルです。
Minimal snippets to reproduce the same XML-to-JSON conversion in code.
JavaScript (ブラウザ / Browser)
const doc = new DOMParser().parseFromString(xml, "application/xml");
if (doc.querySelector("parsererror")) throw new Error("invalid XML");
function toJson(el) {
const obj = {};
for (const a of el.attributes) obj["@" + a.name] = a.value;
for (const c of el.children) {
const v = toJson(c);
obj[c.tagName] = c.tagName in obj ? [].concat(obj[c.tagName], v) : v;
}
const text = el.textContent.trim();
if (el.children.length === 0 && el.attributes.length === 0) return text;
if (text && el.children.length === 0) obj["#text"] = text;
return obj;
}
const json = { [doc.documentElement.tagName]: toJson(doc.documentElement) };Python (xmltodict)
# pip install xmltodict
import json
import xmltodict
# 属性は "@"、テキストは "#text"(本ツールと同じ規約)
data = xmltodict.parse(xml_string)
print(json.dumps(data, indent=2, ensure_ascii=False))
# 逆変換 / Reverse
xml_out = xmltodict.unparse(data, pretty=True)Go (clbanning/mxj)
// go get github.com/clbanning/mxj/v2
import mxj "github.com/clbanning/mxj/v2"
m, err := mxj.NewMapXml([]byte(xmlData)) // 属性は "-" プレフィックス
if err != nil {
// invalid XML
}
jsonBytes, _ := m.JsonIndent("", " ")Shell (yq v4)
# mikefarah/yq は XML 入力をサポート
yq -p=xml -o=json input.xml
# Python ワンライナー(xmltodict)
python -c "import sys,json,xmltodict;print(json.dumps(xmltodict.parse(sys.stdin.read()),indent=2,ensure_ascii=False))" < input.xmlBefore / After 実例 / Before & After
例1: 属性と同名兄弟要素 / Attributes and repeated siblings
<catalog>
<book id="1"><title>XML入門</title></book>
<book id="2"><title>JSON in Practice</title></book>
</catalog>↓
{
"catalog": {
"book": [
{ "@id": "1", "title": "XML入門" },
{ "@id": "2", "title": "JSON in Practice" }
]
}
}例2: テキストのみの要素と混在要素 / Text-only vs mixed elements
<user lang="ja">Koba</user>
<name>Koba</name>↓(それぞれ単独で変換した場合 / converted individually)
{ "user": { "@lang": "ja", "#text": "Koba" } }
{ "name": "Koba" }属性を持つ要素のテキストは #text キーへ、属性のない要素はそのまま文字列値になります。
例3: JSON → XML(エスケープ込み) / Reverse with escaping
{ "note": { "@type": "memo", "body": "A & B < C" } }↓
<?xml version="1.0" encoding="UTF-8"?>
<note type="memo">
<body>A & B < C</body>
</note>The @type key is restored as an attribute, and special characters are escaped automatically.
Why browser-only? / なぜブラウザ完結か
XML payloads you need to convert are rarely public data. SOAP responses carry session tokens and customer records, configuration exports embed internal hostnames, and B2B message feeds contain order and pricing details. Pasting such content into a server-hosted converter transmits all of it to a third party you have no contract with — even if the service only echoes back JSON, the data has already left your machine. This tool performs the entire conversion with the browser's built-in DOMParser and JSON.stringify: no request is sent, nothing is logged, and nothing persists after you close the tab. You can verify this yourself by opening DevTools, switching to the Network panel, and running a conversion — no new entry appears. For regulated environments where external transmission of production data is prohibited, a client-side converter is not just safer but often the only compliant option.
変換対象のXMLには、SOAPレスポンスのセッショントークン、顧客情報、社内ホスト名を含む設定ファイルなど、 外部に出せないデータが含まれがちです。本ツールは DOMParser と JSON.stringify による ブラウザ内処理のみで完結し、ネットワーク送信は一切行いません。DevTools の Network タブが空のままであることで、 いつでも自身で検証できます。
関連ツール / Related Tools
開発をもっと効率的に
PR