How to Convert XML to JSON Without Losing Attributes
Convert XML to JSON without losing data: plan for attributes, repeated elements, mixed content and namespaces. Mapping rules, examples and a free converter.
To convert XML to JSON without losing data, parse the XML with attributes enabled, store each attribute under a prefixed key such as @_id, force repeating elements into arrays, and decide up front how to handle mixed text, namespaces and number coercion. The free XML to JSON converter does the parsing in your browser.
Why is XML to JSON conversion lossy?
XML and JSON describe data differently. XML is a document tree: elements have attributes, can repeat, can mix text with child tags, and carry namespaces. JSON has objects, arrays, strings, numbers, booleans and null, and nothing else. Every XML to JSON converter has to invent a mapping for the concepts JSON lacks, and each converter invents it a little differently.
That is why the same XML file can produce three different JSON documents in three different tools. None of them is wrong. They just made different choices about five things: attributes, repeated elements, mixed content, namespaces and value types. If you know which choice your converter made, you can predict the output and avoid surprises downstream.
| XML construct | Typical JSON shape | What can go wrong |
|---|---|---|
Attribute (id="bk101") | Prefixed key: "@_id" | Silently dropped if the parser ignores attributes |
| Element with attribute and text | Object with "#text" plus attribute keys | Shape changes from string to object when an attribute appears |
| Repeated element | Array | A single occurrence becomes an object, not a one-item array |
| Mixed content (text plus tags) | Child keys plus merged "#text" | Text order and spacing are lost |
Namespaced element (media:cover) | Key with the prefix kept | Prefix is document-specific; stripping it can collide keys |
Text value 02134 | Number or string | Leading zeros vanish when the parser coerces numbers |
What does the json2toon.co converter output for real XML?
The site's converter uses fast-xml-parser (version 5.11.2 at the time of writing) with two settings: ignoreAttributes: false and attributeNamePrefix: "@_". Here is a small catalog that hits every tricky case at once:
<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns:media="http://example.com/media">
<book id="bk101" lang="en">
<title>XML Developer's Guide</title>
<author>Gambardella, Matthew</author>
<price currency="USD">44.95</price>
<tag>xml</tag>
<tag>reference</tag>
<media:cover>cover-101.jpg</media:cover>
</book>
<book id="bk102" lang="en">
<title>Midnight Rain</title>
<author>Ralls, Kim</author>
<price currency="USD">5.95</price>
<tag>fiction</tag>
<note>Ships <b>Monday</b> only</note>
</book>
</catalog>And this is the exact JSON it produces, generated with the same library and options the converter uses:
{
"?xml": {
"@_version": "1.0",
"@_encoding": "UTF-8"
},
"catalog": {
"book": [
{
"title": "XML Developer's Guide",
"author": "Gambardella, Matthew",
"price": {
"#text": 44.95,
"@_currency": "USD"
},
"tag": [
"xml",
"reference"
],
"media:cover": "cover-101.jpg",
"@_id": "bk101",
"@_lang": "en"
},
{
"title": "Midnight Rain",
"author": "Ralls, Kim",
"price": {
"#text": 5.95,
"@_currency": "USD"
},
"tag": "fiction",
"note": {
"b": "Monday",
"#text": "Shipsonly"
},
"@_id": "bk102",
"@_lang": "en"
}
],
"@_xmlns:media": "http://example.com/media"
}
}Read that output closely. Attributes survived. The XML declaration became a "?xml" key. And there are two bugs waiting to happen: tag is an array in the first book but a string in the second, and the note text was glued together as "Shipsonly". The next sections fix each one.
How do I keep XML attributes when converting to JSON?
Turn attribute parsing on explicitly. In fast-xml-parser, ignoreAttributes defaults to true, so a bare new XMLParser() throws attributes away. With default options, the first book above comes out like this:
{
"title": "XML Developer's Guide",
"author": "Gambardella, Matthew",
"price": 44.95,
"tag": [
"xml",
"reference"
],
"media:cover": "cover-101.jpg"
}The book id, the lang and the currency are gone, with no warning. That is the most common way XML to JSON conversion loses data. The fix is two options:
import { XMLParser } from "fast-xml-parser";
const parser = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: "@_",
});
const json = parser.parse(xmlString);The prefix matters because XML allows an attribute and a child element with the same name. Without a prefix, <item id="1"><id>A-7</id></item> would produce two id keys, and one would overwrite the other. Keep the prefix unless you control the schema and know names never collide.
How do I stop single elements turning into objects instead of arrays?
XML has no array type. A parser only creates an array when it sees the same element name twice under one parent. One <book> becomes an object; two become an array. Code that does data.catalog.book.map(...) works on Monday and crashes on Tuesday when the feed returns a single book.
The fix is to tell the parser which paths are always lists. fast-xml-parser takes an isArray callback that receives the tag name and its path:
const parser = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: "@_",
isArray: (name, jpath) =>
["catalog.book", "catalog.book.tag"].includes(jpath),
});
parser.parse(`<catalog><book id="bk101"><title>Solo</title><tag>xml</tag></book></catalog>`);{
"catalog": {
"book": [
{
"title": "Solo",
"tag": [
"xml"
],
"@_id": "bk101"
}
]
}
}Without isArray, the same input returns "book": { ... } and "tag": "xml". If you use the online converter, which does not know your schema, normalize the output in code afterwards: wrap any value that should be a list with Array.isArray(x) ? x : [x].
What happens to mixed content and whitespace?
Mixed content is text interleaved with child tags, as in <note>Ships <b>Monday</b> only</note>. JSON objects are unordered key-value maps, so a converter has to split the text from the tags. With default trimming, fast-xml-parser trims each text fragment and concatenates them into "#text": "Shipsonly". With trimValues: false you get "Ships only", which keeps the spaces but still loses where Monday sat.
If the order matters, as it does for HTML-like content, use preserveOrder: true. The output becomes a list of ordered nodes:
[{"note":[{"#text":"Ships"},{"b":[{"#text":"Monday"}]},{"#text":"only"}]}]That shape is faithful but awkward to query. Most data-oriented XML (RSS feeds, SOAP responses, config files) has no mixed content, so the default mode is fine. Document-oriented XML (DocBook, XHTML, legal texts) usually needs the ordered mode.
How should I handle XML namespaces?
By default the prefix stays in the key, so <media:cover> becomes "media:cover" and the declaration becomes the attribute "@_xmlns:media". That is the safe choice. Prefixes are chosen by the document author, though, so the same namespace might be media: in one file and m: in another.
If you consume feeds from many producers, either map known namespace URIs to fixed prefixes before parsing, or set removeNSPrefix: true and accept that two elements with the same local name in different namespaces will now collide. There is no lossless shortcut here. JSON simply has no namespace concept.
Why did my ZIP code lose its leading zero?
Everything in XML is text. fast-xml-parser converts numeric-looking values to numbers by default, which is why 44.95 above came out as a number. That is usually what you want, but not for identifiers. With the converter's settings, <zip>02134</zip> becomes "zip": 2134. Attribute values are left as strings unless you also enable parseAttributeValue, so code="007" survives.
For identifiers, phone numbers, ZIP codes and long account numbers, set parseTagValue: false and convert the fields you know are numeric yourself:
// parseTagValue: false
{
"r": {
"zip": "02134",
"id": {
"@_code": "007"
}
}
}Should I send XML or JSON to an LLM?
If the converted data is headed into a prompt, the format affects your bill. In the official TOON retrieval benchmark, XML was the most expensive of the six formats tested at 4,909 average tokens per dataset, against 4,308 for pretty-printed JSON and 2,474 for TOON, with accuracy of 70.7%, 71.4% and 72.2% respectively (toon-format benchmark results). Closing tags repeat every field name twice.
Once the XML is clean JSON with consistent arrays, a uniform list like the book catalog can go one step further. Flattened and encoded with @toon-format/toon 4.1.1, the two books look like this:
books[2]{id,title,author,price,currency}:
bk101,XML Developer's Guide,"Gambardella, Matthew",44.95,USD
bk102,Midnight Rain,"Ralls, Kim",5.95,USDTOON averages about 43% fewer tokens than JSON on the official benchmark, about 59% on flat tables, but it is not always the right target. Deeply nested, non-uniform documents often stay smaller as compact JSON. Our XML vs TOON comparison covers the trade-offs, and JSON vs YAML helps if your target is a config file rather than a prompt.
A checklist for converting XML to JSON
- Enable attributes and keep a prefix such as
@_. - Declare array paths for every element that can repeat, or normalize afterwards.
- Decide on mixed content: default mode for data,
preserveOrderfor documents. - Keep namespace prefixes unless you control every producer.
- Turn off number coercion for IDs, ZIP codes and other zero-padded values.
- Validate the result. Once you have JSON, a schema catches shape drift between feeds. The JSON Schema validator runs in the browser.
Going the other way is the same problem in reverse. The JSON to XML converter uses the same @_ convention, so keys with that prefix turn back into attributes. If you are moving tabular data rather than documents, how to convert JSON to CSV covers flattening.
Frequently Asked Questions
How are XML attributes represented in JSON?
JSON has no attributes, so converters store them as ordinary keys with a marker prefix. The json2toon.co converter uses fast-xml-parser with the @_ prefix, so <price currency="USD">44.95</price> becomes an object with "#text": 44.95 and "@_currency": "USD". Many libraries drop attributes by default, so check that setting first.
Why does my XML element sometimes become an array and sometimes an object?
XML has no array type. A parser only creates a JSON array when it sees the same element name more than once. One <book> becomes an object, two become an array. Fix it by declaring which paths are always arrays, for example with the isArray callback in fast-xml-parser, or by normalizing the result in code.
Is XML to JSON conversion reversible?
Only partly. Attributes and namespaces survive if you keep prefixes, but comments, processing instructions, element order and mixed text are often lost or merged. If you need a byte-faithful round trip, use an order-preserving mode such as preserveOrder in fast-xml-parser and accept a noisier JSON shape.
Is it safe to convert XML to JSON online?
It depends on where the parsing happens. The json2toon.co XML to JSON converter parses the document in your browser, so the XML is not uploaded to a server. For confidential files, prefer browser-based or local tools over services that post your document to a remote API.
Recommended Reading
How to Convert JSON to CSV (Including Nested JSON)
Convert JSON to CSV correctly: flatten nested objects, quote commas and line breaks per RFC 4180, handle arrays, and open the result cleanly in Excel.
TOML 1.1: What's New and How to Convert TOML to JSON
TOML 1.1 adds multi-line inline tables with trailing commas, optional seconds in times and new escapes. What changed since 1.0 and how to convert TOML to JSON.
JSON vs YAML: Differences, Use Cases and How to Convert
JSON vs YAML compared on syntax, comments, types, safety and token cost. YAML 1.2 is a strict superset of JSON. When to use each and how to convert both ways.