JSON and XML as interchangeable trees
JSON and XML both represent hierarchical data, but they grew from different traditions. JSON is a lightweight object/array model used by most web APIs. XML is a tagged document model with elements, attributes, namespaces, and mixed content, still central to enterprise messaging, publishing, and many configuration formats.
Converting between them is a structural mapping, not a mere syntax restyle. Names, nesting, and type hints must be chosen deliberately because the two models are not isomorphic. This hub explains that mapping family. For a direct conversion path, open From JSON to XML.
Subtools in this family
- From JSON to XML — take a JSON value and emit an XML document that reflects objects as elements and arrays as repeated children (per the converter’s rules).
- From XML to JSON — parse XML and produce a JSON representation of elements, text, and attributes.
- Format JSON — pretty-print or minify JSON when you need layout control in the same workflow as conversion.
Use the converters when systems on either side of an integration disagree on encoding. Use format-json when the payload is already JSON and you only need readable or compact form before or after a transform.
Where the models diverge
Objects vs elements. JSON objects are unordered maps from string keys to values. XML elements are ordered in document order and may repeat with the same name. A JSON array of objects often becomes repeated sibling elements; a JSON object becomes a set of uniquely named child elements—until a key is illegal as an XML name.
Attributes vs properties. XML attributes are string-only, unordered on an element, and cannot nest. JSON has no separate attribute channel; converters typically map attributes to keys with a conventional prefix (for example @id) or nest them under a reserved object. Round-trips must agree on that convention or attributes and child elements will swap meaning.
Types. JSON distinguishes numbers, booleans, null, strings, arrays, and objects. XML text is always text until a schema (XSD) or convention reinterprets it. Without type metadata, true, 1, and "true" may all survive a round-trip as strings—or a converter may apply heuristics that surprise you.
Namespaces. XML namespaces (xmlns) disambiguate vocabularies. JSON has no native namespace node; prefixes may be flattened into key strings or dropped. Losing namespace information is a common silent failure when XML→JSON→XML is used as a “cleanup” pipeline.
Mixed content. XML allows text and elements interleaved (<p>Hello <em>world</em></p>). JSON trees usually store either a string or children, not both, unless the converter uses an explicit content array. Document-centric XML often needs a richer mapping than data-centric XML.
JSON → XML (conceptual pipeline)
- Parse JSON; reject invalid syntax before any XML is built.
- Choose a root element name (JSON has no single root requirement for a top-level array; converters invent a wrapper).
- Map each object key to a child element or attribute according to naming rules.
- Map arrays to repeated elements with the same tag.
- Escape special characters (
&,<,>, quotes) in text and attributes. - Serialize with or without XML declaration and indentation.
Illegal XML names (keys starting with digits, containing spaces, or colliding with xml reserved prefixes) must be sanitized or rejected. Prefer failing loudly in data pipelines over emitting non-well-formed markup.
XML → JSON (conceptual pipeline)
- Parse as well-formed XML (and optionally validate against a schema elsewhere).
- Represent each element as a JSON object or as a value when it has only text.
- Decide how to encode attributes, repeated children, and empty elements (
""vsnullvs{}). - Collapse or preserve text nodes according to mixed-content policy.
- Emit JSON text; optionally pretty-print for inspection via Format JSON.
Sibling elements with the same name usually become a JSON array. A single child with that name may become a bare object—another round-trip hazard if code assumes arrays always.
Format JSON in a conversion workflow
Conversion errors are easier to diagnose on indented JSON. Minified JSON is better for embedding in logs or transport after you finish editing. Format-json in this family is the layout sibling: it does not move data into XML; it prepares JSON for human or machine consumption around the converters.
Losslessness and when to stop round-tripping
Round-trips are lossy by default unless both directions share a documented convention set (attribute prefixes, array wrapping, type coercion, namespace handling). Safe patterns:
- Convert once at a system boundary and keep a single system of record.
- Store original XML when legal/archival fidelity matters; treat JSON as a working projection.
- Prefer schema-aware tooling (XSD + data binding) for enterprise messages over ad-hoc tree walks.
Unsafe patterns: using JSON as an XML editor (XML→JSON, hand-edit, JSON→XML) for signed documents, namespaces, or mixed content without golden tests.
Characters, encoding, and size
XML documents often declare encoding in the prolog; JSON text in APIs is almost always UTF-8. When converting, ensure the Unicode string in memory is correct before serialization. Control characters illegal in XML 1.0 must be stripped or escaped according to policy—they can appear in JSON strings and break naïve XML writers.
Very large documents stress browser memory. For multi-megabyte exports, prefer streaming converters in your language’s standard ecosystem; browser tools are ideal for samples, fixtures, and debugging slices.
Practical integration examples
- Legacy SOAP/XML service, modern JSON client: map response XML to JSON for the UI; keep request templates in XML when the remote contract demands it.
- Config bridge: maintain internal config as JSON; emit XML for tools that only read XML.
- Fixture building: author data as JSON, convert to XML for a parser harness—keep golden input/output pairs under the same mapping rules as production.
Limitations
These tools do not validate against XSD or JSON Schema, run XSLT, or implement XML Canonicalization (C14N) for signatures. They focus on practical tree projection. For digitally signed XML, use dedicated signature libraries.
Related tooling
Syntax checks: Valid JSON, Valid XML. Pure JSON layout: Pretty-print JSON. Convert when the model must change; format or validate when it stays the same.