XML to JSON: How Attributes, Arrays and Text Are Converted

Published 24 November 2026 · 6 min read

XML and JSON both describe trees, but they are not built the same way. XML has attributes, element order, mixed text and namespaces. JSON has objects, arrays and typed values. Every XML to JSON converter has to make choices, and knowing them saves you from surprises.

Attributes

JSON has no attributes, so a converter has to put them somewhere. A common rule is to prefix the name with @, which keeps them apart from child elements of the same name.

<book id="7"><title>Dune</title></book>

{ "book": { "@id": "7", "title": "Dune" } }

Other tools use an underscore prefix or drop attributes entirely. Pick one and keep it, because the code that reads the JSON depends on it.

Text and attributes together

An element can have both attributes and text. JSON needs a key for the text. A typical choice is #text:

<price currency="USD">44.95</price>

{ "price": { "@currency": "USD", "#text": 44.95 } }

Repeated elements and the single item trap

When an element repeats, the converter makes an array. When it appears once, many tools make a plain object instead. That means the shape of your JSON changes with the data: one item gives an object, two give an array, and code that loops over it breaks on the single case.

  • If you know a field is a list, force it to always be an array.
  • If you cannot, check the shape in your code before looping.

Numbers, booleans and text

XML has no types, so 007, 1e5 and true are all text. Turning them into numbers or booleans is convenient but can damage zip codes, phone numbers and IDs. Convert only when you are sure, and keep codes as strings. Long numbers should stay exact, not rounded to floating point.

Empty elements

An empty element like <note/> becomes null or an empty string. Both are reasonable, but your reader should know which.

Things that do not survive

  • Comments and processing instructions are usually dropped.
  • Element order between different names is lost, because a JSON object is a set of keys.
  • Namespaces are often kept as part of the name, such as ns:item.
  • CDATA sections become ordinary text.

Try it

The XML to JSON converter applies the rules above, lets you change the attribute style, the empty value and the array behavior, and shows the line and column of malformed XML. It runs in your browser, so the file is not uploaded. To go back, use JSON to XML, and to understand how nesting turns into tables see flatten nested JSON into CSV.