Bidirectional XML and JSON Conversion
Converting between XML and JSON is a common task in modern web development. While XML is heavily used in enterprise systems, SOAP APIs, and legacy configurations, JSON is the default data format for modern web APIs, JavaScript applications, and NoSQL databases. This tool offers real-time, client-side bidirectional conversion.
Step-by-Step Guide
- Choose Conversion Direction — Use the ⇄ Swap Direction button to toggle between XML→JSON and JSON→XML mode.
- Paste Content — Paste your source code into the left editor panel.
- Format & Convert — The converted result is generated in the right panel instantly.
- Copy or Download — Click ⎘ Copy or Download to save your result.
Technical Mapping Details
Because XML and JSON have different underlying data models, conversion requires specific mapping rules:
1. Handling XML Attributes
JSON structures objects as key-value pairs, whereas XML allows tags to have attributes (e.g., <book category="fiction">). During XML→JSON conversion, attributes are typically mapped as direct child properties of the object, or nested under an attributes property prefix (like $ or @).
2. Sibling Nodes and Arrays
In JSON, lists are explicitly defined using arrays: [1, 2, 3]. In XML, lists are represented as multiple adjacent tags with the same name:
<author>Author A</author>
<author>Author B</author>
During conversion, these repeating elements are automatically grouped into a single JSON array named author.
Code Snippets
Parse XML to JSON in Node.js (xml2js)
const xml2js = require('xml2js');
const parser = new xml2js.Parser({ explicitArray: false, mergeAttrs: true });
const xmlString = `<book id="1"><title>Clean Code</title></book>`;
parser.parseStringPromise(xmlString)
.then(result => console.log(JSON.stringify(result)))
.catch(err => console.error(err));
Parse JSON to XML in Node.js (xml2js Builder)
const xml2js = require('xml2js');
const builder = new xml2js.Builder({
xmldec: { version: "1.0", encoding: "UTF-8" }
});
const jsonObject = {
book: {
title: "Clean Code",
author: "Robert C. Martin"
}
};
const xml = builder.buildObject(jsonObject);
console.log(xml);
Overcoming Format Limitations
The differences between XML and JSON can sometimes cause issues during conversion. For instance, XML tags can contain both text and child elements at the same time (mixed content), like <text>This is <b>bold</b> text</text>. JSON objects cannot easily represent this structure because key-value pairs are distinct.
In these cases, converters often map the text to a special key (like _ or text) next to the child object. Furthermore, XML namespaces (e.g., <ns:tag>) must be normalized or stripped to prevent invalid JSON property key strings. Understanding these mapping challenges will help you write safer integration code.