Quick Answer: To convert XML to JSON in Python, install xmltodict, call xmltodict.parse(xml_string) to get a dictionary, then use json.dumps to serialize it. In JavaScript, use the xml2js library with parseString. In C#, use Newtonsoft's JsonConvert.SerializeXmlNode. For recurring or high-volume conversions, use a data pipeline to automate the process end to end.

XML to JSON conversion is the process of transforming data stored in XML's hierarchical tag-based format into JSON's key-value pair structure. It is commonly performed to improve API compatibility, reduce payload size, or prepare data for use in modern web applications and data pipelines.

Key Takeaways:

  • After reading this guide, you will be able to convert XML to JSON in Python, JavaScript, C#, and Java using copy-paste-ready code.
  • You will know how XML attributes map to JSON keys, including the @ prefix convention used by xmltodict and Newtonsoft.
  • You will understand how to handle the most common conversion errors: malformed XML, attribute data loss, flattened arrays, and encoding issues.
  • You will know when a script is sufficient and when a data transformation pipeline is the better choice for production workloads.

to Convert XML to JSON: A Step-by-Step Guide

Understanding XML and JSON

XML: Structure and Syntax

XML is designed to store and transfer data. Because it is both human-readable and machine-readable, it works as a versatile tool for interchanging data across systems. The structure of XML is hierarchical, built from nested elements. An XML document typically starts with a declaration, followed by a root element that encompasses all other elements. Every element is enclosed in tags: the opening tag defines the element's name and attributes, and the closing tag marks the element's end.

A simple XML document representing a book looks like this:

<book>
 <title>XML Developer's Guide</title>
 <author>Author Name</author>
 <price>44.95</price>
</book>

Attributes provide additional information about elements and are included within the opening tag. Elements can contain text, other elements, or a combination of both, which allows XML to represent complex data structures. However, XML's verbosity produces larger file sizes, which can affect performance in data-heavy applications.

JSON: Key Features

JSON, or JavaScript Object Notation, is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is derived from JavaScript but is language-independent, making it a popular choice across virtually every programming environment.

JSON structures data using key-value pairs and arrays. Each key-value pair is separated by a colon, and pairs are separated by commas. Curly braces { } define objects; square brackets [ ] define arrays. The same book data in JSON:

{
 "book": {
 "title": "JSON Developer's Guide",
 "author": "Author Name",
 "price": 44.95
 }
}

JSON is less verbose than XML, produces smaller file sizes, and parses faster. It is particularly well-suited for web applications where quick data interchange is critical.

XML vs. JSON: Side-by-Side Comparison

Dimension XML JSON
Structure Hierarchical, tag-based Key-value pairs and arrays
Readability Verbose; tags add noise Compact; easier to scan
Data types Primarily text-based Strings, numbers, booleans, arrays, null
File size Larger due to opening and closing tags Smaller; less markup overhead
Parsing speed Slower Faster
Best for Complex document structures, legacy systems APIs, web apps, modern data pipelines

Benefits of Converting XML to JSON

Improved Data Interoperability and Compatibility

JSON is widely supported across programming languages and platforms, making it easier to integrate with modern web applications, APIs, and mobile apps. XML can be rigid and complex; JSON's straightforward key-value structure enables seamless data integration between systems that would otherwise require custom adapters.

Simplified Data Parsing and Manipulation

JSON's concise format lets developers work with data more efficiently. Python, JavaScript, and Java all include built-in or widely adopted libraries for parsing and generating JSON. Those libraries convert JSON directly into native data structures (objects and arrays) that can be manipulated in code without additional transformation steps.

Enhanced Performance and Scalability

JSON files are smaller than equivalent XML files because they carry no opening and closing tag overhead. Smaller payloads consume less bandwidth, reduce load times for web applications, and lower computational overhead on servers and clients. For applications handling large data volumes or requiring real-time processing, that efficiency compounds quickly.

Preparing for XML to JSON Conversion

Assess XML Data Structure and Complexity

Before converting, examine the XML document's hierarchy: nested elements, attributes, depth of nesting, and any complex data types. This assessment helps you anticipate challenges such as deeply nested structures, repeated elements that need to become arrays, or attributes that need special handling.

Identify Conversion Tools and Libraries

Select a tool based on your programming environment and the complexity of the XML data. Common choices:

  • Python: xmltodict and json (simple), lxml with json (high performance)
  • JavaScript/Node.js: xml2js
  • C#: Newtonsoft Json.NET (JsonConvert.SerializeXmlNode)
  • Java: Jackson XmlMapper
  • No-code: Code Beautify, JSONFormatter, W3Schools XML to JSON tool

Ensure Data Integrity and Quality

Validate the XML document before conversion to confirm it is well-formed and adheres to the required schema. After conversion, review the JSON output to verify accuracy and completeness. Automated validation scripts that compare element counts and key values between the source XML and output JSON catch most data loss issues before they reach production.

Step-by-Step Guide: How to Convert XML to JSON

Step 1: Parse the XML Data

Parse the XML document to break it into a format that can be processed programmatically. Identify all data elements and attributes. Elements form the keys in JSON; attributes require special mapping (covered in the attributes section below). Correct identification at this stage prevents data loss downstream.

Step 2: Convert XML to JSON

Use the appropriate library for your language to transform the parsed XML into JSON. Pay close attention to nested structures: nested XML elements should become nested JSON objects or arrays. Repeated elements at the same level should become JSON arrays, not overwritten scalar values.

Step 3: Check Output for Accuracy

Verify the JSON output against the original XML. Confirm that all elements and attributes are represented correctly. Cross-check sample entries manually, then run automated comparison scripts for large datasets. Resolve discrepancies by adjusting parsing configuration before moving to the next step.

Step 4: Optimize Structure

Remove unnecessary data, rename keys for readability, and flatten redundant nesting where it adds no semantic value. Consistent key naming (camelCase is the JSON convention) improves usability downstream. Streamlining reduces JSON payload size and speeds up parsing in consuming applications.

Step 5: Test and Validate Resulting Data

Run unit tests, integration tests, and functional tests against the JSON output. Validate the JSON against the original XML source to confirm data integrity. Automated validation tools or scripts can compare element counts, key presence, and value types between the two formats to catch any remaining issues.

How to Convert XML to JSON: Code Examples by Language

This section provides complete, copy-paste-ready code for the four most common environments. Each example uses the same book XML structure for consistency.

Python (using xmltodict)

xmltodict is the most widely used Python library for XML to JSON conversion. It parses XML into a Python OrderedDict, which json.dumps serializes to a JSON string.

import xmltodict
import json

xml_string = """
<book>
 <title>XML Developer's Guide</title>
 <author>Author Name</author>
 <price>44.95</price>
</book>
"""

# Parse XML into a Python dictionary
data_dict = xmltodict.parse(xml_string)

# Serialize to JSON
json_output = json.dumps(data_dict, indent=2)
print(json_output)

Expected output:

{
 "book": {
 "title": "XML Developer's Guide",
 "author": "Author Name",
 "price": "44.95"
 }
}

Handling repeated elements: When an XML element may appear once or multiple times, xmltodict will return a dictionary for a single occurrence and a list for multiple. To enforce consistent array output regardless of count, use force_list:

data_dict = xmltodict.parse(xml_string, force_list={"item"})

This ensures that item is always a JSON array, even when only one <item> element exists in the source XML.

For high-performance use cases: Use lxml to parse the XML tree, then serialize with json. lxml handles very large files and complex namespaces more efficiently than xmltodict.

JavaScript (using xml2js)

xml2js is the standard Node.js library for XML to JSON conversion. It supports both callback and async/await patterns.

Install:

npm install xml2js

Callback pattern:

const xml2js = require('xml2js');

const xmlString = `
<book>
 <title>XML Developer's Guide</title>
 <author>Author Name</author>
 <price>44.95</price>
</book>
`;

xml2js.parseString(xmlString, (err, result) => {
 if (err) {
 console.error('Conversion error:', err);
 return;
 }
 console.log(JSON.stringify(result, null, 2));
});

Async/await pattern:

const xml2js = require('xml2js');
const { promisify } = require('util');
const parseString = promisify(xml2js.parseString);

async function convertXmlToJson(xmlString) {
 try {
 const result = await parseString(xmlString);
 return JSON.stringify(result, null, 2);
 } catch (err) {
 console.error('Conversion error:', err);
 }
}

By default, xml2js wraps text content in arrays. To get cleaner output, set explicitArray: false in the options: xml2js.parseString(xmlString, { explicitArray: false }, callback).

C# (using Newtonsoft Json.NET)

Newtonsoft's Json.NET provides JsonConvert.SerializeXmlNode, which converts an XmlDocument or XmlNode directly to a JSON string.

Install via NuGet:

Install-Package Newtonsoft.Json

Example:

using System;
using System.Xml;
using Newtonsoft.Json;

class Program
{
 static void Main
 {
 string xmlString = @"
 <book>
 <title>XML Developer's Guide</title>
 <author>Author Name</author>
 <price>44.95</price>
 </book>";

 XmlDocument doc = new XmlDocument;
 doc.LoadXml(xmlString);

 string jsonOutput = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.Indented);
 Console.WriteLine(jsonOutput);
 }
}

Expected output:

{
 "book": {
 "title": "XML Developer's Guide",
 "author": "Author Name",
 "price": "44.95"
 }
}

Json.NET maps XML attributes using the @ prefix convention (see the attributes section below).

Java (using Jackson XmlMapper)

Jackson's XmlMapper deserializes XML into a Java object tree, then ObjectMapper re-serializes it as JSON.

Maven dependency:

<dependency>
 <groupId>com.fasterxml.jackson.dataformat</groupId>
 <artifactId>jackson-dataformat-xml</artifactId>
 <version>2.17.0</version>
</dependency>

Example:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class XmlToJson {
 public static void main(String[] args) throws Exception {
 String xmlString = "<book>" +
 "<title>XML Developer's Guide</title>" +
 "<author>Author Name</author>" +
 "<price>44.95</price>" +
 "</book>";

 XmlMapper xmlMapper = new XmlMapper;
 JsonNode node = xmlMapper.readTree(xmlString.getBytes);

 ObjectMapper jsonMapper = new ObjectMapper;
 String jsonOutput = jsonMapper.writerWithDefaultPrettyPrinter.writeValueAsString(node);
 System.out.println(jsonOutput);
 }
}

Online Tools (No-Code Option)

For one-off conversions where writing code is unnecessary, several free online tools handle XML to JSON transformation in the browser:

  • Code Beautify XML to JSON Converter: Paste XML on the left, get JSON on the right. Supports pretty-print and minified output.
  • JSONFormatter: Simple interface with basic validation.
  • W3Schools XML to JSON tool: Good for learning and quick tests.

Use online tools for ad hoc conversions during development or debugging. For any conversion that runs on a schedule, handles sensitive data, or processes files larger than a few megabytes, use a script or a data pipeline instead.

How XML Attributes Map to JSON

XML attributes do not have a direct counterpart in JSON. Different libraries handle this mapping in different ways. Understanding the convention your library uses prevents attribute data loss.

The @ Prefix Convention

Both xmltodict (Python) and Newtonsoft Json.NET (C#) use the @ prefix to distinguish attributes from child elements in the JSON output.

XML JSON (xmltodict / Json.NET convention)
<person id="1">Alan</person> {"person": {"@id": "1", "#text": "Alan"}}
<book lang="en"><title>Guide</title></book> {"book": {"@lang": "en", "title": "Guide"}}
<items><item>A</item><item>B</item></items> {"items": {"item": ["A", "B"]}}

The #text key holds the element's text content when attributes are also present.

The Force-Array Edge Case

When an XML element can appear once or multiple times, a converter that does not enforce array output will return a dictionary for one occurrence and a list for two or more. This inconsistency breaks downstream code that expects a consistent type.

Problem:

<!-- One item: xmltodict returns a dict -->
<items><item>A</item></items>

<!-- Two items: xmltodict returns a list -->
<items><item>A</item><item>B</item></items>

Fix in Python:

data_dict = xmltodict.parse(xml_string, force_list={"item"})

Fix in C# (Json.NET): Use JsonConvert.SerializeXmlNode with a custom XmlNodeConverter that sets WriteArrayAttribute on the element.

Always apply force-array handling to any element that represents a collection in your data model, even if the source XML currently contains only one instance.

Common XML to JSON Conversion Errors (and How to Fix Them)

For a deeper look at format-specific import problems, see the XML import errors guide and the JSON import errors guide.

Malformed XML

Problem: The XML document contains unclosed tags, mismatched tags, or illegal characters. All major parsers will throw an exception rather than produce partial output.

Fix: Validate the XML before parsing. In Python:

from lxml import etree

try:
 etree.fromstring(xml_string.encode)
 print("XML is well-formed")
except etree.XMLSyntaxError as e:
 print(f"XML error: {e}")

In C#, XmlDocument.LoadXml throws XmlException on malformed input. Wrap it in a try-catch and log the line number from the exception for fast diagnosis.

Attribute Data Loss

Problem: Some converters silently drop XML attributes if they are not configured to handle them. The resulting JSON contains only element text, with no trace of the original attribute values.

Fix: Confirm your library's attribute handling before running production conversions. With xmltodict, attributes are included automatically using the @ prefix. With xml2js, set mergeAttrs: false (the default) to keep attributes in a separate $ key, or mergeAttrs: true to merge them into the element object.

Single-Element Arrays Flattened to Objects

Problem: A collection element that contains one child is converted to a JSON object instead of a single-item array. Code that iterates over the result breaks when it encounters an object where it expects an array.

Fix: Use force_list in xmltodict (Python) or configure explicitArray: true in xml2js (JavaScript). Apply this setting to all elements that represent collections in your schema, not just the ones that currently have multiple children.

Encoding Issues with Special Characters

Problem: XML files encoded in ISO-8859-1 or Windows-1252 contain characters (accented letters, currency symbols) that are not valid UTF-8. Parsers that assume UTF-8 will throw a UnicodeDecodeError or produce garbled output.

Fix: Detect the encoding from the XML declaration (<?xml version="1.0" encoding="ISO-8859-1"?>) and pass it explicitly to the parser:

with open("data.xml", "rb") as f:
 raw = f.read

data_dict = xmltodict.parse(raw, encoding="iso-8859-1")

In Java, pass the encoding to InputStreamReader before handing the stream to XmlMapper.

When XML to JSON Conversion Belongs in a Data Pipeline

A script or online tool is the right choice for one-off conversions during development. A data pipeline is the right choice when any of the following apply:

Situation Recommended approach
One-off conversion during development Script (xmltodict, xml2js, Json.NET)
Recurring conversion on a schedule Automated ETL pipeline
Multiple XML sources feeding one destination Pipeline with source connectors
Conversion errors need alerting Pipeline with monitoring and alerts
Data needs transformation beyond format change Pipeline with 220+ built-in data transformations
Sensitive data requiring audit logs Governed pipeline with access controls

How Integrate.io Handles XML to JSON at Scale

Integrate.io's data transformation capabilities handle XML ingestion and JSON output automatically, including schema mapping, type coercion, and error alerting, without requiring custom code for each source.

For production pipelines:

  • Connect XML sources (SFTP, cloud storage, APIs) directly to your destination.
  • Apply 220+ built-in transformations to reshape, filter, and enrich data during conversion.
  • Use pipeline monitoring and alerts to catch malformed XML, encoding errors, or schema drift before they affect downstream systems.
  • Maintain full audit logs and access controls for compliance with HIPAA, GDPR, and SOC 2 requirements.

For API-based XML sources, the REST API connector handles authentication, pagination, and response parsing in a single pipeline step.

Talk to an Expert to see how Integrate.io handles your specific XML sources and destinations.

Challenges, Considerations, and Best Practices for XML to JSON Conversion

Addressing Common Challenges and Pitfalls

Complex and deeply nested XML structures produce overly complicated JSON outputs if not handled deliberately. Differences in data types and encoding cause discrepancies during conversion. XML attributes do not have a direct JSON counterpart, which leads to data loss when converters are misconfigured. Handling special characters and preserving hierarchical structure without redundancy require explicit configuration in most libraries.

Implementing Error Handling and Fallback Mechanisms

Validate the XML document before conversion to confirm it is well-formed. During conversion, use try-catch blocks to handle unexpected exceptions gracefully. Log errors with meaningful messages that include the source file name, line number, and element path. For production pipelines, implement fallback mechanisms that preserve the original XML if conversion fails, so no data is silently lost.

Adopting Industry Standards and Guidelines

Use standardized, actively maintained libraries. Follow JSON naming conventions: camelCase for key names, no unnecessary nesting, consistent structure across all records. Document your conversion logic and maintain clear coding standards to support future maintenance. For schema-sensitive applications, validate the JSON output against a JSON Schema definition before loading it into downstream systems.

Effectively Converting XML to JSON

The core steps are: parse the XML, convert using the right library for your language, verify accuracy, optimize structure, and validate the output against the source. The code examples in this guide cover Python, JavaScript, C#, and Java with complete, runnable scripts. The attribute mapping table and force-array guidance address the two most common sources of data loss. The error section covers the four issues that cause the most production incidents.

Decision framework:

Your situation Best approach
Learning or one-off test Online tool (Code Beautify, JSONFormatter)
Scripted conversion in your application Language-specific library (xmltodict, xml2js, Json.NET, Jackson)
Recurring, scheduled, or high-volume conversion Automated data pipeline

Simplify Conversions with Integrate.io

Integrate.io provides the tools to move beyond one-off scripts and automate XML to JSON conversion at any scale. Our platform handles ingestion, transformation, schema mapping, error alerting, and delivery, all without custom code for each source.

Start with a free, 14-day trial to explore our data integration capabilities. Or Talk to an Expert for a personalized walkthrough of how to automate your XML conversion workflows.

FAQs

How do I convert XML to JSON using Python?

Use Python's xmltodict and json libraries. Call xmltodict.parse(xml_string) to get a Python dictionary, then call json.dumps(data_dict, indent=2) to produce the JSON string. For elements that may appear once or multiple times, pass force_list={"element_name"} to xmltodict.parse to ensure consistent array output.

What are the advantages of using JSON over XML?

JSON produces smaller files, parses faster, and maps directly to native data structures in most programming languages. XML is more expressive for complex document schemas and is still common in legacy enterprise systems, but JSON is the standard for modern APIs, web applications, and data pipelines.

Can I convert complex XML structures to JSON seamlessly?

Yes. Use Python's xmltodict library with force_list for repeated elements, or Newtonsoft Json.NET in C# for attribute-rich structures. For deeply nested XML, validate the JSON output against the original XML schema before deploying to confirm that no elements were dropped or flattened incorrectly.

What is the difference between XML and JSON?

XML uses opening and closing tags to define a hierarchical document structure and is primarily text-based. JSON uses key-value pairs and arrays, supports native data types (numbers, booleans, null), and produces smaller, faster-parsing files. XML is better suited for document-centric data; JSON is better suited for data exchange between applications.

How do I handle XML namespaces when converting to JSON?

XML namespaces (e.g. xmlns:ns="http://example.com") are included as attributes in the parsed output. In xmltodict, namespace prefixes appear as part of the key name (e.g. "ns:title"). To strip namespaces, use lxml with etree.QName(element).localname to extract the local name before converting. In Json.NET, use XmlNamespaceManager to resolve prefixes before serialization.

What is the best Python library for XML to JSON conversion?

xmltodict is the best choice for simplicity: it handles attributes, nested elements, and repeated elements with minimal configuration. For high-performance or large-file scenarios, use lxml to parse the XML tree and json to serialize the result. lxml is faster and uses less memory on files above a few megabytes.

Integrate.io: Delivering Speed to Data
Reduce time from source to ready data with automated pipelines, fixed-fee pricing, and white-glove support
Integrate.io