XML to JSON

Paste or upload XML to convert it into JSON. CDATA is not supported.

Pasted text and chosen files stay on this device. Nothing is sent to a server.

Drop a file here, choose one, or paste.

No output yet Convert to see the result here.

How to use it

  1. 1

    Paste the XML.

  2. 2

    Read the rule line; a consumer has to agree with the attribute prefix and the array rule.

What it does

The three undecided places in XML-to-JSON are attributes, repeated elements and text. Each has more than one defensible mapping, so the conversion states its rule and reports where it applied.

Walk the XML tree and emit JSON. Attributes become members under a declared prefix; repeated sibling elements become an array; text becomes a string value. Report where each rule applied.

Why it works this way

Attributes and child elements are the same information in XML and different things in JSON. Without a naming rule a document with both an attribute and an element of the same name loses one, silently.

Whether a single element becomes an array is a choice with no correct answer, and it is the one that breaks consumers most often — an API that returns one item and then two changes the shape of the response.

Mixed content — text and elements as siblings — has no JSON equivalent. It is reported rather than approximated, because approximating it drops one of the two.

Examples

<a x="1">t</a>
{"a": {"@x": "1", "#text": "t"}}
the attribute and the text both survive, under declared keys
<r><i>1</i><i>2</i></r>
{"r": {"i": ["1", "2"]}}
repeated siblings became an array, and the count says so

Inputs and outputs

  • XML text
  • attributes: prefixed key / @-prefixed / ignored
  • repeated elements: array always / array only when repeated
  • JSON text
  • the rule applied, with counts for attributes, arrays and text nodes

Edge cases

  • attributes and elements with the same name
  • namespaces
  • CDATA sections
  • mixed content
  • entities and character references
  • an element that is both repeated and has attributes

Frequently asked questions

Why is my single element an array?

Because the array rule is set to always, so the shape does not change when a second item appears. It can be switched to repeat-only.

Where did the attributes go?

Into keys with the declared prefix, and the report counts them, so none are dropped unnoticed.

Related tools

Sources

  • W3C XML 1.0, section 2.3 (Common syntactic constructs)