JSON to XML

Convert JSON objects, array payloads, and nested API structures into clean, standardized XML documents.

How to Convert JSON to XML Online

1

Paste JSON Data

Paste any JSON object, array payload, or API response on the left, click Upload, or click Sample.

2

Configure Root & Spacing

Customize your root XML element tag name (e.g. root or response) and select indentation.

3

Export XML Document

Converts instantly in real time. Click Copy or Download to export clean .xml files.

Tool Options

Root XML Tag Name

Customizes the enclosing root element tag wrapper (e.g. <root>, <response>, <data>).

XML Indentation Spacing

Select formatting style: 2 Spaces, 4 Spaces, or Compact single-line XML payload output.

XML Entity Sanitization

Automatically sanitizes reserved XML entities (&lt;, &gt;, &amp;, &quot;) inside text values.

Your Data Privacy

Web Tool
Privacy-First Architecture
Most of our web tools process your data entirely in-browser. Where server processing is technically required, payloads are evaluated statelessly in-memory and are never stored, saved, or logged.
REST API
Stateless In-Memory Processing
When you use our API endpoints, your requests are processed strictly in-memory without persistent database storage, disk logging, or data retention.
Want to learn more about how we safeguard your information and infrastructure?
Read our full Privacy Policy for detailed security standards, data retention principles, and compliance guarantees.

What does the JSON to XML Converter do?

The JSON to XML Converter transforms JavaScript Object Notation (JSON) objects, array payloads, and nested API structures into clean, well-formed Extensible Markup Language (XML) documents in real time. Executing 100% in-browser on blueutils.com, it supports custom root element tag wrappers (e.g. <root>, <response>, <data>), configurable indentation spacing (2 spaces, 4 spaces, or compact single-line output), and automatic sanitization of reserved XML entity characters (&lt;, &gt;, &amp;, &quot;).

  • Real-Time Zero-Latency Parsing: Converts JSON to XML as you type, providing live before-and-after byte size metrics (X B → Y B).
  • Custom Root Element Wrapping: Encloses multiple top-level keys or raw arrays inside a customizable, sanitized root tag.
  • Configurable Indentation & Compact Modes: Format with 2 Spaces, 4 Spaces, or Compact single-line XML output.

Core Concepts & Technical Specifications

  1. Hierarchy & Document Wrapping:
    • Single Root Enforcement: Standard XML strictly requires exactly one root element enclosing the entire document. If JSON input contains multiple top-level properties or a top-level array, the converter automatically wraps them in the user-specified root tag.
    • Array Item Serialization: Array elements are serialized into uniform sibling nodes under their respective parent key.
  2. XML Entity Sanitization:
    • Reserved XML characters in string values are escaped: & to &amp;, < to &lt;, > to &gt;, " to &quot;, and ' to &apos;.
    • Tag names with invalid identifiers (spaces, special symbols, leading digits) are sanitized into valid XML element names (_123_tag).
  3. In-Browser Privacy:
    • All conversions run locally in browser memory.
    • No data is transmitted to external servers, logged, or retained.

How to use the tool?

  1. Input JSON Data:
    • Paste any JSON object, array payload, or API response into the left editor, click Upload to load a local file, or click Sample to load a pre-configured payload.
  2. Configure XML Options:
    • Set the Root XML Tag Name (e.g. root, response, data).
    • Select 2 Spaces, 4 Spaces, or Compact indentation from the top toolbar.
  3. Copy or Download:
    • Converted XML appears instantly in the right editor. Click Copy to copy to your clipboard or Download to save as output.xml.

Pipeline & Contextual Workflows

  • Legacy SOAP & Enterprise Feeds: Transform modern JSON payloads from REST microservices into XML schemas required by enterprise banking, insurance, and SOAP endpoints.
  • Reverse XML Parsing: Convert XML feeds and RSS documents back into structured JSON datasets using XML to JSON Converter.
  • Configuration Conversions: Convert JSON configurations to human-readable YAML with JSON to YAML Converter.

REST API Integration

blueutils.com provides a free REST API endpoint (POST https://blueutils.com/api/json/to-xml) for automated data transformation pipelines, ETL ingestion, and enterprise service bus (ESB) bridges.

API Request Parameters

Name Type Description Example
rawText / json String / Object Input JSON object, array, or raw text payload to convert to XML. "{\"user\":{\"id\":101,\"name\":\"John Doe\"}}"
rootName String Optional root XML wrapper element tag name (defaults to "root"). "response"
indent Number / String Optional indentation spaces (2, 4, or 'compact'). Default is 2. 2

API Request Payload Examples

cURL (Using Direct JSON Object)

curl -X POST https://blueutils.com/api/json/to-xml \
  -H "Content-Type: application/json" \
  -d '{
    "json": {
      "user": {
        "id": 101,
        "name": "John Doe",
        "role": "admin"
      }
    },
    "rootName": "response",
    "indent": 2
  }'

cURL (Using Raw String)

curl -X POST https://blueutils.com/api/json/to-xml \
  -H "Content-Type: application/json" \
  -d '{
    "rawText": "{\"user\":{\"id\":101,\"name\":\"John Doe\"}}",
    "rootName": "response",
    "indent": 2
  }'

Python

import requests

url = "https://blueutils.com/api/json/to-xml"
payload = {
    "json": {
        "user": {
            "id": 101,
            "name": "John Doe"
        }
    },
    "rootName": "response",
    "indent": 2
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.json())

Java

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String jsonPayload = """
            {
                "rawText": "{\\"user\\":{\\"id\\":101,\\"name\\":\\"John Doe\\"}}",
                "rootName": "response",
                "indent": 2
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://blueutils.com/api/json/to-xml"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
            .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

API Response Parameters

Name Type Description Example
isValid Boolean Returns true if JSON to XML conversion succeeded. true
result String Converted clean XML document string payload. "<response>\n <user>\n <id>101</id>\n </user>\n</response>"
data Object / Array Parsed native object/array representation returned when input is valid JSON. {"user":{"id":101,"name":"John Doe"}}
originalSize Number Byte size of raw input JSON payload in UTF-8. 45
resultSize Number Byte size of converted XML document in UTF-8. 62
error String Detailed error explanation returned on invalid syntax. "Invalid JSON syntax: Unexpected token '}' (Line 2)"

API Response Payload Examples

Success Response (HTTP 200 OK)

{
  "isValid": true,
  "result": "<response>\n  <user>\n    <id>101</id>\n    <name>John Doe</name>\n  </user>\n</response>",
  "data": {
    "user": {
      "id": 101,
      "name": "John Doe"
    }
  },
  "originalSize": 45,
  "resultSize": 62
}

Validation Failure Response (HTTP 400 Bad Request)

{
  "isValid": false,
  "error": "Invalid JSON syntax: Unexpected token '}' at position 15 (Line 1, Column 16)"
}

Rate Limit Exceeded Response (HTTP 429 Too Many Requests)

{
  "error": "API rate limit exceeded. Please wait or contact support@blueutils.com."
}

Why use an API to convert JSON to XML?

Automating JSON to XML conversions streamlines legacy integration pipelines:

  • Enterprise Interoperability: Seamlessly bridges modern microservices with legacy SOAP, ERP, and banking systems.
  • LLM Context Efficiency: AI models often make tag balancing errors with complex XML. Offloading XML generation to an API ensures deterministic XML tag hierarchy without wasting tokens.
  • Strict Entity Sanitization: Automatically escapes dangerous XML characters (<, >, &) to prevent parser errors in downstream ingestion jobs.

Native Usage

Convert JSON to XML locally across terminal environments and programming runtimes:

Linux / macOS (yq CLI)

# Convert JSON file to XML using yq
yq -p=json -o=xml '.' input.json

Windows (PowerShell)

# Using Node.js xml-js in PowerShell
node -e "const { js2xml } = require('xml-js'); const data = JSON.parse(require('fs').readFileSync('data.json')); console.log(js2xml({ root: data }, { compact: true, spaces: 2 }));"

Python (xml.etree.ElementTree)

import json
import xml.etree.ElementTree as ET

def json_to_xml(json_obj, tag="root"):
    elem = ET.Element(tag)
    if isinstance(json_obj, dict):
        for key, val in json_obj.items():
            elem.append(json_to_xml(val, tag=key))
    elif isinstance(json_obj, list):
        for item in json_obj:
            elem.append(json_to_xml(item, tag="item"))
    else:
        elem.text = str(json_obj)
    return elem

data = {"user": {"id": 101, "name": "John Doe"}}
root_elem = json_to_xml(data, tag="response")
print(ET.tostring(root_elem, encoding="unicode"))

Java (Jackson Dataformat XML)

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import java.io.File;

public class Main {
    public static void main(String[] args) throws Exception {
        ObjectMapper jsonMapper = new ObjectMapper();
        Object data = jsonMapper.readValue(new File("data.json"), Object.class);

        XmlMapper xmlMapper = new XmlMapper();
        String xml = xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(data);
        System.out.println(xml);
    }
}

Frequently Asked Questions (FAQ)

How do I convert JSON to XML online?

Paste your raw JSON object or array payload into the input editor, configure your root XML wrapper tag (e.g. root or response), and choose your indentation. The XML document renders in real time.

How does the converter handle XML reserved characters?

Special XML characters inside string literals (such as <, >, &, ", and ') are automatically encoded as valid XML entities (&lt;, &gt;, &amp;, &quot;, &apos;) to preserve document integrity.

How are JSON arrays converted to XML nodes?

JSON arrays are unpacked into repetitive sibling XML elements wrapped by their parent key or enclosing root tag, matching standard XML list conventions.

Can I generate compact single-line XML for API payloads?

Yes. Select Compact from the indentation dropdown to remove all whitespace and newlines, producing minimal payload size for high-throughput HTTP requests.

Is my JSON data uploaded or stored on external servers?

No. All JSON parsing and XML conversions run 100% client-side directly in your browser. Your sensitive data never leaves your device.

Rate Limits

UI Limits
100 uses per 15 minutes
Max payload size: 5 MB
API Limits
5 requests per 60 minutes
Max payload size: 256 KB
Need higher API rate limits, increased payload sizes, or custom developer solutions?
Contact our engineering team at support@blueutils.com for custom rate limit increases, higher quota allocations, or tailored enterprise integrations.