XML to JSON Conversion
Learn how to parse XML documents into JSON format. Covers element-to-key mapping, text content extraction, and common challenges in XML-to-JSON transformation.
Detailed Explanation
Converting XML to JSON is essential when consuming data from SOAP APIs, RSS feeds, or enterprise services that speak XML, while your application uses JSON internally.
A typical XML document:
<user>
<id>42</id>
<name>Alice</name>
<email>alice@example.com</email>
<verified>true</verified>
</user>
Converts to this JSON:
{
"user": {
"id": "42",
"name": "Alice",
"email": "alice@example.com",
"verified": "true"
}
}
Key conversion challenges:
- Everything becomes a string. XML element text content has no type information.
<id>42</id>becomes"42"(string), not42(number). Post-processing is needed for type coercion. - Attributes vs. elements. XML can store data in both attributes and child elements. A common convention is to prefix attribute names with
@in the JSON output:<user id="42">becomes{ "@id": "42" }. - The root element dilemma. The XML root element (
<user>) becomes a wrapper key in JSON. Some converters strip the root to produce a flatter output. - Single child vs. array ambiguity. If a parent has one
<item>child, should the JSON be"item": {...}(object) or"item": [{...}](array)? This is XML-to-JSON's biggest design decision.
Common conventions:
| Convention | Attributes | Text content | Arrays |
|---|---|---|---|
| Parker | Dropped | Direct value | Based on count |
| BadgerFish | @attr prefix |
$ key |
Always arrays |
| Yahoo/JsonML | Positional | Mixed into array | Positional |
Recommendation: For most use cases, the simple convention of element-to-key mapping with @-prefixed attributes and explicit array hints provides the best balance of readability and fidelity.
Use Case
Consuming a third-party SOAP API response in a modern React frontend by converting the XML response body to JSON for state management and rendering.