Handling XML Attributes in JSON Conversion
Learn how XML attributes are represented in JSON and how to control attribute generation during JSON-to-XML conversion. Covers @-prefix convention and attribute vs element choices.
Detailed Explanation
XML attributes are metadata attached to elements that have no direct equivalent in JSON. Handling them correctly is critical for faithful bidirectional conversion.
XML with attributes:
<product id="A001" currency="USD">
<name>Widget</name>
<price>29.99</price>
</product>
JSON representation (using @ prefix convention):
{
"product": {
"@id": "A001",
"@currency": "USD",
"name": "Widget",
"price": "29.99"
}
}
Common conventions for attributes in JSON:
| Convention | Attribute representation | Example |
|---|---|---|
@ prefix |
"@id": "A001" |
Most popular, used by xml2js |
- prefix |
"-id": "A001" |
BadgerFish convention |
_attributes object |
"_attributes": { "id": "A001" } |
Explicit grouping |
| Flat (no distinction) | "id": "A001" |
Simple but lossy |
When to use attributes vs. elements:
In XML design, the general guideline is:
- Attributes for metadata (IDs, types, formats, language codes)
- Elements for actual data content
<!-- Preferred: id as attribute, content as elements -->
<user id="42">
<name>Alice</name>
<email>alice@example.com</email>
</user>
<!-- Less common: everything as elements -->
<user>
<id>42</id>
<name>Alice</name>
<email>alice@example.com</email>
</user>
JSON-to-XML attribute generation:
When converting JSON to XML, you can use the @ prefix to control which fields become attributes:
{
"book": {
"@isbn": "978-0-13-468599-1",
"@lang": "en",
"title": "The Pragmatic Programmer",
"author": "David Thomas"
}
}
Produces:
<book isbn="978-0-13-468599-1" lang="en">
<title>The Pragmatic Programmer</title>
<author>David Thomas</author>
</book>
Important constraints: XML attribute values must be strings and cannot contain child structure. Attributes cannot be repeated on the same element. Attribute order is not guaranteed to be preserved by XML parsers.
Use Case
Converting an XML product catalog that uses attributes for SKU identifiers and currency codes into JSON for a web storefront, while preserving the attribute distinction for accurate round-trip conversion back to XML.