Skip to main content

XML to JSON & JSON to XML Converter

Convert XML data to JSON and JSON data to XML instantly. Features include auto-detection, validation, custom formatting, and a live structural tree view preview.

Input Data
Ready
Lines 0
Characters 0
Output Size 0 B

Advertisement

Data Interchange & Schema Bridge XML & JSON Round Trip

XML to JSON & JSON to XML Mapping: Attributes, Arrays, and Root Rules

Enterprise payment gateways, RSS feeds, and shipping carriers frequently speak verbose XML, whereas web frontends, mobile apps, and Node or Python services expect compact JSON objects. Converting between XML and JSON is never a simple one to one syntax swap because XML supports tag attributes, mixed text nodes, and repeated sibling tags, whereas JSON natively provides typed primitives and explicit arrays. Knowing the exact mapping conventions makes round trip conversions predictable and safe.

1. Mapping XML Attributes and Mixed Text via @attributes and #text

XML lets every opening element attach key/value attributes alongside nested child tags or plain text. Plain JSON objects have no separate attribute namespace, so flattening <price currency="USD">29.99</price> naively drops either the currency code or the dollar value.

To preserve complete structure cleanly in both directions, the converter follows the standard @attributes and #text notation whenever an element combines metadata with content. A clean childless tag without attributes (<name>John</name>) compiles straight into "name": "John", and an empty self closing flag (<active />) maps to "". As soon as attributes or mixed children enter, attributes nest neatly under "@attributes" and inline node text maps onto "#text" so reverse JSON to XML conversion reconstructs original attributes accurately.

Source XML With Attributes & Siblings:
<order id="901">
  <total currency="EUR">49.50</total>
  <tag>express</tag>
  <tag>insured</tag>
</order>
Converted JSON Output:
{
    "order": {
        "@attributes": { "id": "901" },
        "total": {
            "@attributes": { "currency": "EUR" },
            "#text": "49.50"
        },
        "tag": ["express", "insured"]
    }
}

2. The Single Element Array Trap in XML to JSON Parsing

When parsing repeated sibling elements (<tag>express</tag> followed by <tag>insured</tag>), the recursive DOM walker automatically promotes duplicate element names into a JavaScript array (["express", "insured"]). However, raw XML documents without an attached XSD schema never signal whether a single occurrence like <tag>express</tag> represents a scalar field or a one element list.

Consequently, an XML feed containing two line items yields an array, whereas an invoice containing only one line item converts to a plain object or string under that key. When wiring converted SOAP or RSS feeds into TypeScript or React frontends, normalize fields explicitly (Array.isArray(val) ? val : [val]) before looping with .map() so single item responses never crash UI rendering.

Mixed content nodes inside document oriented XML behave subtly as well. Suppose a paragraph element contains inline emphasis such as <p>Buy <b>two</b> items</p>: JSON keys cannot interleave text position inside object dictionaries cleanly, so text fragments gather inside "#text" while child element "b" stores "two" separately. That structural asymmetry explains why document styling belongs inside XML or HTML markup, whereas structured API records fit JSON objects naturally.

3. Root Tag Selection & Tag Name Sanitization in JSON to XML

Converting JSON arrays or unstructured dictionaries back to strict XML enforces two W3C specification rules that JSON ignores completely:

JSON Input Pattern Generated XML Behavior Why Rule Applies
{"order": {...}} Uses <order> directly as root below XML prolog Single top key object avoids redundant nested wrapper tags
[{"id": 1}, {"id": 2}] or {"a": 1, "b": 2} Wraps children cleanly inside <root>...</root> W3C XML strictly prohibits multiple sibling roots or bare arrays
{"2026_metric": 99} or {"user name": "A"} Normalizes to <_2026_metric> / <user_name> XML element names cannot contain spaces or begin with digits
{"flag": null} Serializes cleanly as <flag /> Null or undefined leaves become self closing empty elements

4. Comments, Namespaces, and Round Trip Type Loss

Because untyped XML carries no native numeric or boolean metadata, every leaf string such as <count>42</count> or <enabled>true</enabled> serializes into quoted JSON strings ("42" and "true") during XML to JSON extraction rather than guessing whether postal codes with leading zeros (02138) should lose their padding into integers. Downstream parsers that compute arithmetic or boolean branches should convert extracted string leaves explicitly after validating expected fields.

Two structural traits of XML also shape what arrives inside JSON. First, XML comments (<!-- note -->) and processing instructions are omitted silently because valid RFC 8259 JSON forbids comment syntax completely. Second, scoped namespace tags such as <soap:Body> remain intact as exact prefixed property keys ("soap:Body") while their xmlns:soap="..." bindings sit inside @attributes so full SOAP envelopes retain their namespaces across conversions.

Conversely, serializing JSON back toward XML writes unquoted number and boolean text cleanly below the UTF-8 prolog <?xml version="1.0" encoding="UTF-8"?>, while escaping reserved entities (<, >, &, ", ') automatically inside both element bodies and attribute values. Note how invalid JSON property names such as spaces or numeric keys sanitize automatically on output: for instance, converting [{"2026_code": "A1"}] wraps the root array cleanly inside <root><_2026_code>A1</_2026_code></root> rather than producing syntax breaking numeric tag names.

Advertisement

5. Tree View Debugging, Auto Detect, and Practical Workflows

  • Auto Detect Delimiter Check: Clicking Auto Detect inspects the trimmed leading character (< triggers XML to JSON; { or [ triggers JSON to XML), validating structure through strict DOMParser or JSON.parse() before rendering output.
  • Pretty Print vs. Minify Export: Toggle Output Format between human readable 4 space JSON / indented XML and compact single line wire output before clicking Copy or Save (which exports automatically with the correct .json or .xml extension while tracking output bytes in the stats bar).
  • Interactive Tree View Exploration: Switch from Code View to Tree View to expand or collapse deeply nested JSON branches rendered through safe client DOM nodes with colorized types and array counts.
  • Legacy API Middleware & RSS Inspection: Backend engineers debugging carrier shipping rates, government tax gateways, or podcast RSS feeds regularly paste captured XML logs to verify JSON payloads quickly, or convert JSON configuration templates into clean UTF-8 XML requests for legacy SOAP endpoints.

All XML parsing, JSON serialization, file drops, and tree inspection execute strictly inside browser JavaScript memory with zero network transmissions, keeping sensitive legacy ERP responses and internal API configurations private on your machine.