CSV and XML are everywhere — spreadsheet exports, legacy APIs, enterprise feeds — but most modern code wants JSON. Converting between them is straightforward once you understand the mapping rules and the gotchas (everything in CSV is a string; XML attributes and repeated elements need special handling). This guide covers both conversions in JavaScript, Python, and the browser.
Scope: this article is the broad how-to covering both CSV → JSON and XML → JSON in one place. If you need XML specifically — attributes, text nodes, repeated elements, and namespaces in depth — read XML to JSON Conversion: Attributes, Text Nodes, Arrays, and Namespaces. For the reverse direction see JSON to XML.
Converting CSV to JSON
A CSV file is rows of comma-separated values, usually with a header row. The natural JSON representation is an array of objects, one per row, keyed by the header:
# CSV
id,name,active
1,Ada,true
2,Bob,false// JSON
[
{ "id": "1", "name": "Ada", "active": "true" },
{ "id": "2", "name": "Bob", "active": "false" }
] Notice every value is a string — CSV has no types. Converting "1" to a number or "true" to a boolean is a separate coercion step you must do deliberately.
CSV to JSON in JavaScript
For trusted, simple CSV you can split manually — but real CSV has quoted fields containing commas and newlines, so use a proper parser like papaparse in production:
// Minimal parser — only safe for simple, unquoted CSV
function csvToJson(csv) {
const [header, ...rows] = csv.trim().split('\n');
const keys = header.split(',');
return rows.map((row) => {
const values = row.split(',');
return Object.fromEntries(keys.map((k, i) => [k, values[i]]));
});
}
// Production — handles quotes, embedded commas, newlines
import Papa from 'papaparse';
const result = Papa.parse(csvText, { header: true, dynamicTyping: true });
// dynamicTyping converts "1" → 1 and "true" → true automaticallyCSV to JSON in Python
import csv, json
with open('data.csv', newline='') as f:
rows = list(csv.DictReader(f)) # list of dicts keyed by header
print(json.dumps(rows, indent=2))Converting XML to JSON
XML is trickier because it has concepts JSON lacks: attributes, text nodes, and repeated-vs-single elements. There's no single "correct" mapping, so pick a convention and apply it consistently.
<!-- XML -->
<user id="1">
<name>Ada</name>
<role>admin</role>
<role>editor</role>
</user>// A common JSON mapping
{
"user": {
"@id": "1", // attribute, prefixed with @
"name": "Ada", // single child → value
"role": ["admin", "editor"] // repeated child → array
}
}XML to JSON in JavaScript
import { XMLParser } from 'fast-xml-parser';
const parser = new XMLParser({ ignoreAttributes: false, attributeNamePrefix: '@' });
const obj = parser.parse(xmlString);
// In the browser you can also use DOMParser and walk the node tree manually.XML to JSON in Python
import xmltodict, json
doc = xmltodict.parse(xml_string) # attributes become "@name" keys
print(json.dumps(doc, indent=2))Mapping Gotchas to Watch For
- Types are lost. CSV and XML values arrive as strings. Coerce numbers and booleans explicitly — don't assume a parser did it.
- Single vs. repeated elements. One
<role>becomes a value; two become an array. Decide whether a field should always be an array to avoid surprising consumers. - Attributes vs. child elements. Pick a prefix convention (commonly
@) and document it. - Empty values and whitespace. Empty XML elements and trailing CSV commas can produce
null,"", or missing keys depending on the parser.
BOM and Encoding Quirks
Files exported from Excel and some Windows tools start with a UTF-8 BOM (0xEF 0xBB 0xBF). Strip it before parsing or your first header / element name will silently include it. RFC 8259 prohibits a BOM at the start of JSON, so any converter you build should remove it from the input rather than copy it into the output.
TSV vs CSV (and Other Delimiters)
"CSV" isn't always comma-separated. Tab-separated values (TSV) are common in engineering pipelines because tabs almost never appear inside values, so you can skip the quoting machinery. European Excel exports often use ;. If your output looks like one weird column, the file uses a different delimiter than your parser expects — switch the delimiter or use a library that detects it.
XML Namespaces
XML elements can be qualified with a namespace prefix (e.g. <soap:Envelope>) bound by an xmlns declaration. JSON has no namespace concept, so most converters take one of three paths: keep the prefix in the key ("soap:Envelope"), strip it, or store xmlns declarations as @xmlns:* attributes. Keeping the prefix is the only lossless option. For the deep dive, see XML to JSON Conversion.
Validate and Format the Result
After converting, confirm the output is well-formed and readable:
- Check it parses with the JSON validator — see How to Validate JSON.
- Pretty-print it for review — see How to Format JSON.
- If the conversion produced not-quite-valid JSON (single quotes, trailing commas), JSON Fix repairs it instantly.
Frequently Asked Questions
How do I convert CSV to JSON?
Parse the CSV into rows and map each to an object keyed by the header — use csv.DictReader in Python or a library like papaparse in JavaScript. Remember that all values start as strings; coerce types yourself.
Why are all my CSV-to-JSON values strings?
CSV is untyped — every field is text. Enable type coercion (e.g. papaparse's dynamicTyping) or convert numbers and booleans explicitly after parsing.
How do I handle XML attributes when converting to JSON?
Most converters map attributes to keys with a prefix such as @ (e.g. @id). Choose a convention and apply it consistently so downstream code knows where to look.
Why does my XML-to-JSON output sometimes give an object and sometimes an array?
A single child element maps to a value; a repeated element maps to an array. Configure your parser to always treat certain elements as arrays if consumers expect a consistent shape.
Convert, Validate & Format in Your Browser
- How to Convert JSON to CSV (and Back) — the reverse direction, with a one-click converter
- JSON to CSV Converter — convert JSON ⇄ CSV in your browser
- XML to JSON Conversion — attributes, text nodes, arrays, and namespaces in depth
- JSON to XML — the reverse direction, with a JSON ⇄ XML converter
- JSON Validator — confirm your converted JSON is valid
- JSON Fix — repair not-quite-valid converter output
- How to Format JSON — pretty-print the result
- What Is JSON? — the target format's types and rules