XML to JSON: Normalize Single and Repeated Items
Many feed consumers call .map on item lists. With this converter a single item is a value, while repeated elements with the same name become an array. Normalize it before processing the feed.
Worked example
One XML item and the actual JSON
<feed><item>alpha</item></feed>
{
"feed": {
"item": "alpha"
}
}Two XML items and the actual JSON
<feed><item>alpha</item><item>beta</item></feed>
{
"feed": {
"item": [
"alpha",
"beta"
]
}
}Normalize an already parsed JS object
const value = parsed.feed?.item; const items = value == null ? [] : Array.isArray(value) ? value : [value];
Steps
- Convert a feed with zero, one, and two items so you can see each shape before writing a parser.
- If the field is missing, use an empty list. If it's already an array, use it directly. Otherwise, wrap its value once.
- Apply the rule only to known repeatable fields such as feed.item. Other fields may legitimately be scalars.
What to check
- Do not infer array shape from the size of one real-world feed. Include an empty feed in your regression tests.
- The snippet handles shape only. Validate item values separately if your consumer requires a specific schema.