How are XML attributes represented when converting to JSON?

Dark navy cover card with the title 'How are XML attributes represented when converting to JSON?' in white and a green accent bar

When you convert XML attributes to JSON, most tools turn each attribute into an ordinary key with an @ in front, so <book id="7"> becomes {"book": {"@id": "7"}}. If the element also has text, the text goes under a reserved key such as #text or $. A few conventions add attributes with no prefix, and some drop them entirely.

Why XML attributes need a special mapping in JSON

XML attributes need special handling because JSON has only objects, arrays and plain values. There's no separate slot for "metadata about this element", so a converter has to fold attributes into the same object as the child elements.

Two problems follow. An attribute and a child can share a name: <item id="1"><id>2</id></item> has two different things called id. And once an element with text gets attributes, it becomes an object, so the text needs a key of its own. For a refresher on the XML side, see what is an XML file.

The common pattern: @ for attributes, #text for text

The most common mapping prefixes attribute names with @ and puts text under #text. Stefan Goessner's 2006 article Converting Between XML and JSON lists it as a set of patterns:

XML JSON
<e name="value" /> "e": {"@name": "value"}
<e name="value">text</e> "e": {"@name": "value", "#text": "text"}

xmltodict, the Python library, uses the same defaults. Its README says: "The default value for attr_prefix is @ and the default value for cdata_key is #text." Its own example turns <plus a="complex"> element as well </plus> into "plus": {"@a": "complex", "#text": "element as well"}.

The prefix makes the round trip work. Going back to XML, xmltodict turns keys that start with attr_prefix into attributes and the cdata_key into text.

Six XML to JSON conventions compared

Each named convention handles attributes and text differently, and the choice decides whether your attributes survive. The xmljson library documentation summarises them:

Convention Attributes Text content
BadgerFish "@ to prefix attributes" "$"
Goessner / xmltodict @ prefix #text
GData "attributes added as-is" "$t"
Yahoo "attributes added as-is" "content"
Abdera grouped under "attributes" children under "children"
Parker "ignore attributes" tail nodes

Here is <p id="main">Hello</p> under each rule:

  • BadgerFish: {"p": {"@id": "main", "$": "Hello"}}
  • Goessner / xmltodict: {"p": {"@id": "main", "#text": "Hello"}}
  • GData: {"p": {"id": "main", "$t": "Hello"}}
  • Yahoo: {"p": {"id": "main", "content": "Hello"}}
  • Abdera: the attributes sit in their own "attributes" object, separate from "children"
  • Parker: the id is gone; only the text is kept

xmljson's BadgerFish example adds a child element: <p id="main">Hello<b>bold</b></p> gives {"p": {"$": "Hello", "@id": "main", "b": {"$": "bold"}}}.

The same docs list a seventh, Cobra. It puts sorted attributes under "attributes" "even when empty", so every element has the same shape.

Which conventions lose attributes or break round trips

Parker loses attributes by design, and the no-prefix styles can lose them by collision. Everything else keeps them, at the cost of extra keys.

Parker: the xmljson docs give its rule as "ignore attributes", and add that "The Parker convention absorbs the root element by default." That's fine for record-style data where everything lives in elements. Use it on <price currency="EUR">9</price> and the currency is gone.

GData and Yahoo keep attributes with no marker. In <item id="1"><id>2</id></item>, the attribute and the child now want the same JSON key. Converting back, nothing in the JSON says which keys were attributes.

The @ styles have gaps too. xmltodict's README admits "It does not preserve every XML nuance (attribute order, mixed content ordering, multiple top-level comments)." Goessner wrote that "In an ideal world, the resulting JSON structure can be converted back to its original XML document easily," then described cases where the result is "irreversible but semantically equivalent."

How to keep attributes when converting in JavaScript

In the browser, DOMParser gives you every attribute through Element.attributes. MDN's attributes reference notes "It is a NamedNodeMap, not an Array, so it has no Array methods," and "You can enumerate through an element's attributes using for...of."

A small converter using the @ / #text pattern:

function toJson(el) {
  const out = {};
  for (const attr of el.attributes) out['@' + attr.name] = attr.value;
  for (const child of el.children) out[child.tagName] = toJson(child);
  const text = el.children.length ? '' : el.textContent.trim();
  if (text) {
    if (!el.attributes.length) return text;
    out['#text'] = text;
  }
  return out;
}

const doc = new DOMParser().parseFromString('<p id="main">Hello</p>', 'application/xml');
console.log({ p: toJson(doc.documentElement) }); // { p: { "@id": "main", "#text": "Hello" } }

This sketch breaks on two things a real converter must handle. Repeated child tags overwrite each other instead of becoming an array, and text mixed between children is lost. The XML to JSON conversion guide covers the repeated-tag problem and how libraries force arrays.

To just see the result, the XML to JSON converter parses with the browser's DOMParser, so the XML stays on your machine.

How to pick a convention

Pick the convention your consumer expects first, and the @ / #text pattern when nobody has decided yet.

  1. Something already consumes the JSON? Match it. A Python service using xmltodict expects @ and #text.
  2. You need to convert back to XML? Use a prefixed style (BadgerFish or @ / #text). Unprefixed styles can't tell attributes from children.
  3. Attributes carry data? Rule out Parker.
  4. The JSON is for humans only? Take the least noisy style your library supports.

My take: default to @ / #text. Goessner wrote it down, xmltodict ships it, and most people reading your JSON will recognise it on sight. The cost is uglier JavaScript: book['@id'] instead of book.id.

Attribute values come out as strings, so id="7" becomes "7" unless your code converts it. Read JSON.parse and large numbers before turning long IDs into numbers. If you have a schema for the target JSON, validate the output against JSON Schema to catch a dropped attribute straight away.

FAQ

Why do XML attributes get an @ in JSON?

JSON has no attributes, so converters store them as ordinary keys. The @ prefix marks which keys came from attributes, so they don't clash with child elements of the same name and can be turned back into attributes later.

Where does the element's text go when it also has attributes?

It goes under a reserved key. Goessner's patterns and xmltodict use #text, BadgerFish uses $, GData uses $t and the Yahoo convention uses content.

Why did my converter drop all the attributes?

Some conventions ignore them on purpose. The Parker convention ignores attributes, and some libraries only include them when an option is switched on, such as xmltodict's xml_attribs.

Can I change the @ prefix to something else?

In many libraries, yes. xmltodict, for example, lets you set attr_prefix and cdata_key. Keep the same settings when you convert back, or the attributes won't be recognised.

Sources