DEV Community

Sanjaya Sahu
Sanjaya Sahu

Posted on

XML to JSON: 6 Conversion Traps That Break Your Data

Converting XML to JSON looks trivial until real data shows up. XML has attributes, mixed content, namespaces and repeated elements, and JSON has none of those concepts. Here is where conversions go wrong.

1. Attributes versus child elements

<user id="7"><name>Ada</name></user> has an attribute and a child. Converters usually pick a prefix such as @id or _id. Decide on a convention and keep it consistent across your pipeline.

2. One item versus many

A single <item> becomes an object, but two <item> elements become an array. Code that expects an array breaks on the one-item case. Normalize with a helper that wraps single values.

3. Everything is a string

XML has no types. <age>30</age> converts to "30", and <active>false</active> becomes the truthy string "false". Convert types explicitly after parsing.

4. Mixed content

<p>Hello <b>world</b></p> has text and elements interleaved. JSON cannot represent order without extra structure, so text often gets lost or reordered.

5. Namespaces

Prefixes like soap:Envelope survive as part of the key. Decide whether to keep or strip them, and do it before the data reaches application code.

6. Whitespace and CDATA

Pretty-printed XML produces whitespace-only text nodes. CDATA sections should become plain strings.

Convert and inspect

Check the output on a real sample before wiring it into code. This converter runs in your browser, so your XML is never uploaded.

Try it: XML to JSON

Related: XML Validator, JSON to XML and XML to YAML. All 590+ tools at webdevtoolbox.com run client-side.

Top comments (0)