XML Converter · Tutorial

How to convert an XML API response to JSON

6 min readbeginnerUpdated

A supplier’s API returns orders as XML, but your app works with JSON. You will convert the response, choose options that make the JSON easy to use in code, and check the shape.

What you need

Steps

  1. Paste the response

    Load the example: two orders with attributes, a currency on each total and one or two items each.

  2. Read the shape

    orders.order is an array of two objects. Attributes appear as @id and @status, and each total becomes {"@currency": "EUR", "#text": 59.8}.

  3. Make arrays consistent

    The second order has one item, so item is an object there but an array in the first. Tick Always use arrays so code can always loop over item.

    for (const order of data.orders[0].order) {
      console.log(order['@id'], order.item.length);
    }
  4. Use real numbers

    Keep Numbers and true/false ticked so 4200 and true arrive as a number and a boolean, not strings.

Try it yourself

Opens the XML Converter with this tutorial's sample loaded.

Try it now

Common mistakes

Relying on the shape of one sample
A sample with one item hides the fact that items repeat. Use Always use arrays or a larger sample.
Converting very large feeds in production code
For production, use a streaming XML parser in your language. This tool is ideal for exploring data and building test fixtures.

Next steps

Go back to the XML Converter, or keep going with one of these: