Data•9 min read
XML and JSON Conversion: Complete Data Format Guide
Convert between XML and JSON formats. Learn syntax differences, conversion strategies, and best practices.
By Andy Pham
XML and JSON Conversion: Complete Data Format Guide
XML and JSON are the two most common data interchange formats. Understanding how to convert between them is essential for integration work.
XML vs JSON Comparison
| Feature | XML | JSON |
|---|---|---|
| Verbosity | High | Low |
| Readability | Moderate | Good |
| Attributes | Yes | No |
| Comments | Yes | No |
| Namespaces | Yes | No |
| Schema validation | XSD | JSON Schema |
| Size | Larger | Smaller |
Basic Conversion Examples
Simple Element
<!-- XML -->
<person>
<name>John</name>
<age>30</age>
</person>
{
"person": {
"name": "John",
"age": 30
}
}
Arrays
<!-- XML -->
<fruits>
<fruit>Apple</fruit>
<fruit>Banana</fruit>
<fruit>Orange</fruit>
</fruits>
{
"fruits": {
"fruit": ["Apple", "Banana", "Orange"]
}
}
Attributes
<!-- XML -->
<book id="1" category="fiction">
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
</book>
{
"book": {
"@id": "1",
"@category": "fiction",
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald"
}
}
JavaScript Conversion
XML to JSON
// Using fast-xml-parser
const { XMLParser } = require('fast-xml-parser');
const parser = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: '@_'
});
const xml = '<person><name>John</name></person>';
const json = parser.parse(xml);
JSON to XML
const { XMLBuilder } = require('fast-xml-parser');
const builder = new XMLBuilder({
ignoreAttributes: false,
attributeNamePrefix: '@_'
});
const json = { person: { name: 'John' } };
const xml = builder.build(json);
Python Conversion
import xmltodict
import json
# XML to JSON
xml = '<person><name>John</name></person>'
data = xmltodict.parse(xml)
json_str = json.dumps(data)
# JSON to XML
data = json.loads(json_str)
xml = xmltodict.unparse(data, pretty=True)
Conversion Challenges
Mixed Content
<p>Hello <b>World</b>!</p>
JSON doesn't have a standard way to represent mixed content.
Namespaces
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>...</soap:Body>
</soap:Envelope>
Namespaces require special handling in conversion.
Attribute vs Element
<!-- These are semantically similar but structurally different -->
<person name="John"/>
<person><name>John</name></person>
Best Practices
- Use consistent attribute prefixes (@, _, etc.)
- Handle arrays explicitly
- Preserve data types when possible
- Validate after conversion
- Document conversion rules
Try Our Conversion Tools
- XML to JSON - Convert XML to JSON
- JSON to XML - Convert JSON to XML
- XML Validator - Validate XML syntax
Conclusion
XML and JSON serve different needs. Understanding conversion helps integrate systems and migrate data between formats.