JSON Formatter Hub

Free online JSON formatter, validator, and developer tools.

How to Convert JSON to CSV, XML, and YAML (With Examples)

JSON is the universal interchange format, but that doesn’t mean every tool that needs your data speaks JSON. Spreadsheet users want CSV. Enterprise integrations often expect XML. Infrastructure engineers configure in YAML. Knowing how to convert JSON to each format β€” and the traps to avoid along the way β€” is a daily developer skill.

1. JSON to CSV

CSV works naturally for flat arrays of objects β€” each object becomes a row, each key becomes a column header.

JavaScript: JSON to CSV

function jsonToCsv(jsonArray) {
  if (!Array.isArray(jsonArray) || jsonArray.length === 0) {
    throw new Error('Input must be a non-empty array');
  }
  const headers = [...new Set(jsonArray.flatMap(obj => Object.keys(obj)))];
  const escape = (value) => {
    if (value === null || value === undefined) return '';
    const str = String(value);
    if (str.includes(',') || str.includes('"') || str.includes('\n')) {
      return '"' + str.replace(/"/g, '""') + '"';
    }
    return str;
  };
  const rows = jsonArray.map(obj => headers.map(h => escape(obj[h])).join(','));
  return [headers.join(','), ...rows].join('\n');
}

Python: JSON to CSV

import csv
import json
import io

def json_to_csv(json_data: list[dict]) -> str:
    if not json_data:
        return ''
    all_keys = list(dict.fromkeys(key for obj in json_data for key in obj.keys()))
    output = io.StringIO()
    writer = csv.DictWriter(output, fieldnames=all_keys, extrasaction='ignore', restval='')
    writer.writeheader()
    writer.writerows(json_data)
    return output.getvalue()

Flattening nested JSON for CSV

// JavaScript flatten function
function flattenObject(obj, prefix = '') {
  return Object.keys(obj).reduce((acc, key) => {
    const fullKey = prefix ? `${prefix}.${key}` : key;
    const value = obj[key];
    if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
      Object.assign(acc, flattenObject(value, fullKey));
    } else if (Array.isArray(value)) {
      acc[fullKey] = value.join('|');
    } else {
      acc[fullKey] = value;
    }
    return acc;
  }, {});
}

2. JSON to XML

The mapping rules

JSONXML Representation
Object {"key": "val"}<key>val</key>
Array [1, 2, 3]Repeated <item> elements
StringText node content
NumberText node content
BooleanText node: true or false
null<key xsi:nil="true" />

JavaScript: JSON to XML

function jsonToXml(obj, rootElement = 'root', indent = 0) {
  const pad = '  '.repeat(indent);
  if (obj === null) return `${pad}<${rootElement}/>`;
  if (typeof obj !== 'object') {
    return `${pad}<${rootElement}>${escapeXml(String(obj))}</${rootElement}>`;
  }
  if (Array.isArray(obj)) {
    return obj.map(item => jsonToXml(item, 'item', indent)).join('\n');
  }
  const children = Object.entries(obj)
    .map(([key, val]) => jsonToXml(val, key, indent + 1))
    .join('\n');
  return `${pad}<${rootElement}>\n${children}\n${pad}</${rootElement}>`;
}

3. JSON to YAML

JSON is a strict subset of YAML. Converting from JSON to YAML is about readability: YAML drops the quotes, braces, and brackets of JSON in favor of indentation-based structure.

JavaScript: JSON to YAML

// npm install js-yaml
const yaml = require('js-yaml');
const fs   = require('fs');

const data = JSON.parse(fs.readFileSync('data.json', 'utf8'));
const yamlStr = yaml.dump(data, {
  indent: 2,
  lineWidth: -1,
  noRefs: true
});

fs.writeFileSync('output.yaml', yamlStr);

Python: JSON to YAML

# pip install pyyaml
import json
import yaml

with open('data.json') as f:
    data = json.load(f)

with open('output.yaml', 'w') as f:
    yaml.dump(data, f, default_flow_style=False, allow_unicode=True, sort_keys=False)

YAML gotchas when converting from JSON

# YAML 1.1 interprets these as booleans, not strings:
country: NO     # parsed as false in YAML 1.1
flag: yes       # parsed as true

# Fix: always quote ambiguous string values
country: "NO"

4. Which Format to Choose

Use CaseBest FormatReason
Spreadsheet analysis, Excel, Google SheetsCSVNative import; no programming required
Flat tabular data exportCSVSmallest file size, widest tool support
Enterprise integrations, SOAP servicesXMLSchema validation (XSD), namespace support
Kubernetes / Docker Compose configYAMLEcosystem standard
CI/CD pipelines (GitHub Actions, GitLab CI)YAMLEcosystem standard
API responses, web data transferJSONNative browser support, fast parsing

Converting in the Browser

Our JSON Formatter tool includes an Export button that converts your JSON to CSV, XML, and YAML directly in your browser. No data is sent to a server β€” the conversion happens entirely client-side.

Further Reading