Converting JSON Arrays as Root Elements
Handle the case where the top-level JSON value is an array, not an object. Learn root element wrapping strategies and naming conventions for array-based XML output.
Detailed Explanation
When the top-level JSON value is an array, the conversion to XML requires special handling because XML demands exactly one root element.
A JSON array as root:
[
{ "name": "Alice", "age": 30 },
{ "name": "Bob", "age": 25 },
{ "name": "Carol", "age": 35 }
]
Conversion strategies:
Strategy 1: Generic <root> wrapper
<root>
<item>
<name>Alice</name>
<age>30</age>
</item>
<item>
<name>Bob</name>
<age>25</age>
</item>
<item>
<name>Carol</name>
<age>35</age>
</item>
</root>
Strategy 2: Semantic wrapper names
<users>
<user>
<name>Alice</name>
<age>30</age>
</user>
<user>
<name>Bob</name>
<age>25</age>
</user>
<user>
<name>Carol</name>
<age>35</age>
</user>
</users>
Strategy 3: Indexed elements
<root>
<item index="0">
<name>Alice</name>
<age>30</age>
</item>
<item index="1">
<name>Bob</name>
<age>25</age>
</item>
<item index="2">
<name>Carol</name>
<age>35</age>
</item>
</root>
Why this is tricky:
- JSON arrays are ordered collections with no inherent container name. The array itself has no label, just content.
- XML requires every element to have a tag name. A root array needs both a wrapper element name and an item element name.
- The converter cannot infer semantic names (
users/user) from the data alone -- it uses generic names unless configured otherwise.
Arrays of primitives:
["red", "green", "blue"]
<root>
<item>red</item>
<item>green</item>
<item>blue</item>
</root>
Best practice: Allow the user to specify the root and item element names. Default to <root> and <item>, but provide options for customization. This gives flexibility without losing data.
Use Case
Converting a JSON API response that returns a bare array of search results into XML for feeding into an XSLT transformation pipeline that produces an HTML report.