Basic JSON to XML Conversion
Learn the fundamentals of converting a flat JSON object to XML format. Understand how keys become element names, values become text content, and structure is preserved.
Detailed Explanation
Converting JSON to XML is a common task when integrating modern REST APIs with legacy SOAP services or enterprise systems that require XML input.
A simple JSON object:
{
"name": "DevToolbox",
"version": "2.0",
"active": true
}
Converts to this XML:
<root>
<name>DevToolbox</name>
<version>2.0</version>
<active>true</active>
</root>
Key mapping rules:
- Each JSON key becomes an XML element. The key
"name"maps to<name>...</name>. - Primitive values become text content. Strings, numbers, and booleans are placed as text nodes inside the element.
- A root element is required. JSON does not need a single root, but XML requires exactly one root element. Converters typically wrap the output in
<root>or a user-specified tag name. - Booleans and numbers are stringified. JSON
truebecomes the text"true"in XML, and42becomes"42". XML has no native type system for element content.
Data type considerations:
- JSON
nullcan map to an empty element<field/>or an element withxsi:nil="true". - Strings containing XML special characters (
<,>,&,",') must be escaped or wrapped in CDATA sections. - Key names that are not valid XML element names (e.g., starting with a digit or containing spaces) must be sanitized.
Lossless round-tripping between JSON and XML is not always possible because XML has features (attributes, namespaces, mixed content) with no direct JSON equivalent. However, for simple flat objects the conversion is straightforward and reversible.
Use Case
Sending product data from a Node.js microservice to a legacy ERP system that only accepts XML payloads over a SOAP interface, where each product is a flat JSON object with name, SKU, and price fields.