JSON versus XML

How JSON and XML differ in data model, types, schemas and editability, what changes when you convert between them, and how to check that formatted output stays valid.

JSON and XML both represent structured data as plain text, and many tools format, validate or convert between them. They are built on different models, though, so a conversion is not a simple change of punctuation. This guide covers what each format stores, what conversion and formatting change, and how to choose between them.

What each format represents

JSON (JavaScript Object Notation) is specified in RFC 8259 and ECMA-404. It describes data with objects (unordered name–value pairs), arrays (ordered lists), strings, numbers, the literals true and false, and null. Its structure maps directly to the dictionaries, lists and scalar values found in most programming languages.

XML (Extensible Markup Language) is a W3C Recommendation. It describes a tree of elements, and each element can carry attributes, text, child elements or a mix of text and children. XML was designed for documents as well as data. It therefore supports features that JSON lacks, including namespaces, comments, processing instructions and mixed content, such as a paragraph whose text contains inline emphasis elements.

What converting between JSON and XML actually changes

Converting rewrites the stored characters and the structure that holds the data. It is not a visual effect. No single standard mapping exists between the two formats, so different converters can produce different output from the same input. The main decisions a converter makes are these:

  • Attributes versus elements: an XML value can be an attribute or a child element. JSON has only name–value pairs, so converters often mark attributes with a prefix such as @ or a dedicated key, and the conventions vary.
  • Arrays: XML has no array type, only repeated sibling elements. When converting XML to JSON, an element that appears once may become a single value, while the same element appearing twice becomes an array. Consumers then receive inconsistent shapes unless a schema or configuration fixes the mapping.
  • Data types: in XML, everything is text unless a schema says otherwise. JSON distinguishes strings, numbers, booleans and null. Converting XML to JSON requires guessing types or keeping everything as strings. Converting JSON to XML loses the type distinction unless it is recorded somewhere.
  • Root element: an XML document has exactly one root element. A JSON text can be an array or even a bare value, so a wrapper element may need to be invented.
  • Features with no JSON equivalent: comments, namespaces, processing instructions and mixed content are often dropped or flattened into awkward key structures.
  • Ordering: XML element order is meaningful. JSON object member order is not guaranteed to be preserved by every parser.

The following matched pair is illustrative. It shows one possible mapping, written by hand, and is not the output of any specific tool.

{
  "book": {
    "id": "b42",
    "title": "Example Title",
    "tags": ["reference", "data"],
    "inStock": true,
    "pages": 320
  }
}
<book id="b42">
  <title>Example Title</title>
  <tags>
    <tag>reference</tag>
    <tag>data</tag>
  </tags>
  <inStock>true</inStock>
  <pages>320</pages>
</book>

Several choices in this example are arbitrary. The id became an attribute, but it could have been an element. The array name "tags" required inventing a singular "tag" element name. In the XML, true and 320 are plain text with no type. Converting this XML back to JSON could therefore yield "pages": "320" as a string, or a lone tag as a single string rather than a one-item array. Because of this, a round trip is not reliably reversible unless the converter is configured for your data or a schema guides it.

What formatting and pretty-printing change

A formatter, beautifier or minifier changes only whitespace and line breaks. It should not change the data. In JSON, whitespace between tokens is insignificant, so pretty-printing and minifying preserve meaning as long as the contents of strings are untouched.

XML needs more care. Whitespace inside text content can be significant, especially in mixed content or in elements marked with xml:space="preserve". Re-indenting such content can alter the text that a consumer reads. If your XML carries document-style content, compare the text values before and after formatting rather than assuming the reformatted version is equivalent.

Comparing JSON and XML on the same criteria

Criterion | JSON | XML
Data model | Objects, arrays, scalar values | Tree of elements with attributes and text
Built-in types | String, number, boolean, null | Text only; types come from a schema
Comments | Not allowed by the specification | Supported
Namespaces | None | Supported
Mixed text and markup | Not natively supported | Supported
Schema options | JSON Schema (separate specification) | DTD, XML Schema (XSD), RELAX NG
Querying and transformation | JSONPath, JSON Pointer, language-native access | XPath, XSLT, XQuery
Verbosity | Generally more compact, with no closing tags | Closing tags and attributes add characters
Hand editing | Short syntax, but strict about commas and quotes | More verbose, but tags label every value
Round-trip conversion | Not guaranteed to reverse cleanly to XML | Not guaranteed to reverse cleanly to JSON

The table compares features, not performance. No measured data on file size, parsing speed or memory use was available for this guide. Treat claims that one format is always smaller or faster as unverified until they are tested with your own data and parsers.

Which format suits your intended result

  • Choose JSON for web APIs, configuration consumed by code, and data that maps naturally to lists and key–value records. Its types and simple structure reduce conversion work in most modern languages.
  • Choose XML for document-like content with inline markup, for data that must mix vocabularies through namespaces, or when you need mature validation and transformation tools such as XSD and XSLT.
  • Use whatever the destination requires when you integrate with an existing system, standard or partner. Converting adds a mapping layer that someone must maintain.
  • If you must convert repeatedly, define the mapping explicitly. Decide how attributes, arrays, types and empty values are represented, and test a round trip on representative samples instead of relying on default converter behavior.

Will the output remain valid and usable where you need it?

Both formats are plain text, so they survive copy and paste better than styled or Unicode-substituted text. Strict parsers still reject small changes that are easy to miss when text passes through editors, chat apps or word processors:

  • Curly quotation marks in place of straight double quotes make JSON invalid and can break XML attribute values.
  • Trailing commas after the last item in an object or array are invalid in standard JSON, even though some editors and relaxed parsers accept them.
  • Comments are not part of standard JSON. Files that include them, such as some configuration formats, need a parser that explicitly allows them.
  • Unescaped characters break XML: a raw ampersand or less-than sign in text must be escaped or placed in a CDATA section.
  • RFC 8259 requires UTF-8 for JSON exchanged between systems and forbids adding a byte order mark. XML can declare its encoding, and a mismatch between the declaration and the actual bytes causes parse errors.
  • Non-breaking spaces or invisible characters pasted from rich-text sources may be rejected or may end up inside values.

Some caveats concern data integrity rather than syntax. RFC 8259 says object member names should be unique, but parsers handle duplicates differently, and some keep only the last value. The specification also warns that numbers beyond the precision of standard double-precision floating point may not be represented exactly by every implementation, so large identifiers are safer as strings. After any conversion or edit, run the result through a validator, or better, the actual parser used by the destination system.

Indentation matters for readability. Consistent line breaks make nesting easier to follow visually and with assistive technology, because a minified single line forces a reader to track brackets or tags character by character. No test results on how specific screen readers announce JSON or XML were available, so check with the tools your audience actually uses. For human readers, a pretty-printed copy alongside the machine-facing version is usually the safer choice.

Handling sensitive data and parser security

Pasting data into a web-based formatter, validator or converter may send it to a third-party server, unless the tool documents that processing happens locally in the browser. Do not paste API keys, tokens, personal data or confidential records into a service whose handling you have not verified. Remove or mask sensitive values first, or use a local tool such as an editor extension, a command-line utility or your language's standard library.

Each format also carries parser-level risks. XML parsers that resolve external entities can be exposed to XML external entity (XXE) attacks, so disable DTD and external entity processing for untrusted input unless you need it. Parse JSON with a real JSON parser rather than evaluating it as code. Treat any converter output as untrusted input, just like the original data.

Gaps in this comparison

This guide relies on the published specifications and general, verifiable behavior of the formats. It does not include benchmarks, tests of particular converters or online tools, or observations of specific screen readers. Where those details affect your decision, test with your own data, your target parser and your audience's tools before standardizing on a format or conversion workflow.