XML to JSON

What is an Xml To Json?

Many enterprise systems, SOAP services, RSS feeds and government APIs still return XML, while modern applications and JavaScript code work much more easily with JSON. This converter parses XML and produces an equivalent JSON structure you can use directly in code or tools.

How to use it

  1. Paste well-formed XML.
  2. Copy the generated JSON.

Example

Input:

<book id='7' lang='en'>
  <title>Clean Code</title>
  <author>Robert C. Martin</author>
  <tag>programming</tag>
  <tag>craft</tag>
</book>

A typical JSON result (shown with single quotes):

{ 'book': { '@id': '7', '@lang': 'en', 'title': 'Clean Code',
  'author': 'Robert C. Martin', 'tag': ['programming', 'craft'] } }

How XML maps to JSON

XML and JSON have different data models, so converters follow conventions:

  • Attributes are usually prefixed, such as @id or _attributes, to keep them apart from child elements.
  • Repeated elements with the same name become arrays.
  • Text content of an element that also has attributes goes into a key such as #text.
  • All values are strings, because XML has no number or boolean types without a schema.

The single-item array trap

If a document has one <tag>, it becomes a string; with two, an array. Code that expects an array will break on single-item responses. Normalise in your code by wrapping single values in an array where a list is expected.

Notes

Namespaces are kept in element names, comments are dropped and the order of mixed content is not always preserved.

Frequently Asked Questions

How are XML attributes represented in JSON?

Usually as keys with a prefix such as @ or inside an attributes object, so they do not clash with child elements.

Why is a field sometimes an array and sometimes a string?

Repeated elements become arrays, but a single occurrence becomes a plain value. Normalise this in your code.

Are numbers converted to JSON numbers?

Usually not. XML text is untyped, so values stay as strings unless you convert them.

Can I convert JSON back to XML?

Yes, use the JSON to XML converter, but attribute and array conventions must match for a perfect round trip.