Convert XML to JSON
Many legacy APIs and data exports use XML while modern applications expect JSON. Converting XML to JSON allows you to use familiar JavaScript object access patterns instead of XPath or DOM traversal. This example converts a products XML document showing how element hierarchies become nested objects, attributes become prefixed keys, and repeated elements become JSON arrays. The converter handles CDATA sections, XML namespaces, and the standard edge cases around text-only nodes and mixed content.
Example
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<product id="p001" category="electronics">
<name>Wireless Keyboard</name>
<price currency="USD">49.99</price>
<stock>142</stock>
<tags>
<tag>wireless</tag>
<tag>keyboard</tag>
<tag>bluetooth</tag>
</tags>
</product>
<product id="p002" category="accessories">
<name>USB-C Hub</name>
<price currency="USD">29.99</price>
<stock>87</stock>
</product>
</catalog>FAQ
- How are XML attributes represented in JSON?
- XML attributes are typically converted to JSON keys prefixed with @ or placed in an _attributes object, depending on the converter. The resulting JSON key name convention varies between conversion libraries.
- What happens to XML namespaces during conversion?
- Namespace prefixes are usually retained as part of the JSON key name (e.g., ns:element becomes "ns:element"). Some converters strip namespaces — check your output if namespace-qualified element names are important.
- Can all XML documents be converted to JSON?
- Most document XML converts cleanly. However, XML features like processing instructions, comments, and mixed content (elements with both text and child elements) require special handling that varies by tool.
Related Examples
Convert JSON to YAML
JSON and YAML represent the same data structures but use very different syntax. ...
XML Sitemap for a WebsiteAn XML sitemap tells search engine crawlers which pages to index, how often they...
Format a REST API ResponseREST APIs return compact JSON that is hard to read at a glance. Paste this examp...