Badgerfish Convention: Using @ and $ Prefixes

The Badgerfish convention is a lightweight set of rules designed to convert XML data into JSON without losing metadata or structural integrity. Because XML supports attributes, text nodes, and child elements within a single tag, direct conversion to JSON’s key-value format can lead to ambiguity. Badgerfish solves this by standardizing the transformation, specifically using the @ prefix to represent XML attributes and the $ prefix to represent text content.

The @ Prefix for XML Attributes

In standard XML, elements can contain attributes that store metadata (for example, <user id="42" active="true">). In JSON, an object only contains keys and values.

To distinguish an XML attribute from a nested XML element, Badgerfish prefixes the attribute name with an @ symbol.

This prefix prevents naming collisions if an element contains both an attribute and a child element with the same name.

The $ Prefix for Text Content

XML elements can contain both text and attributes simultaneously. When an element is converted into a JSON object to accommodate its attributes, the raw text content inside the XML element needs a dedicated key. Badgerfish assigns the $ key to hold this text value.

If an element contains no attributes, namespaces, or child elements, some implementations simplify the text to a standard key-value pair, but strict Badgerfish retains the $ property to maintain consistent parsing rules across complex structures.

Comprehensive Example

Consider an XML element that combines attributes, nested text, and child nodes:

<book id="bk101" inStock="true">
  <title lang="en">Developing with JSON</title>
  <price currency="USD">29.99</price>
</book>

Converted using the Badgerfish convention:

{
  "book": {
    "@id": "bk101",
    "@inStock": "true",
    "title": {
      "@lang": "en",
      "$": "Developing with JSON"
    },
    "price": {
      "@currency": "USD",
      "$": "29.99"
    }
  }
}

Why These Prefixes Matter

  1. Lossless Bi-directional Conversion: The explicit separation of @ (attributes) and $ (text) ensures that a JSON document can be converted back into valid XML without losing the original structure.
  2. Namespace Management: Badgerfish also uses the @ prefix for XML namespaces (e.g., @xmlns), allowing complex namespace scopes to be represented accurately within standard JSON syntax.
  3. Predictable Parsing: Developers and parsers can programmatically determine whether a key represents an attribute or a value by inspecting the first character of the property name.